Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two wifi modules M1 and M2 that connect to my access point. I have an android phone that connects to the same access point. I have a socket server on my android phone and the two modules join to the server as clients. Now my question is, is it possible to send a string message from my phone to module M1 without having to send anything to M2. I want to choose between clients to send the message to. Is it even possible in Java?

Ok, here goes.

//setting up server
ServerSocket serverSocket = new ServerSocket(8000, 0, IPaddress);

//creating a client socket to accept it
Socket clientSocket = serverSocket.accept();

Now, I accept the client in a seperate thread so that the main thread does not freeze becauz accept() function is blocking.

I don't know how to create a new thread every time a new client connects. Also I dont know how to limit the number of clients that can connect. I need at most 5 clients and no more.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
93 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes, it is possible. You need to maintain a separate connection to each client. The ServerSocket class has an accept() function which returns a Socket object. That object represents a connection between two points, your server and one client. You can call ServerSocket.accept() multiple times in a loop to accept all incoming connections. Each Socket object returned will be for a different client.

In order to have the server send a message to a specific client, it will need to know which socket belongs to which client, so the clients will have to send some message to the server identifying themselves, and the server will need to read and interpret that message. Then it can respond with the appropriate response for that specific client.

Post your code if you are still having trouble.

UPDATE because you added code to the question: See the Android Documentation about creating threads. That will be a lot of reading beyond this post on stackoverflow.

As to accepting connections and starting threads, just do it in a loop:

for(int i = 0; i<5; i++){
    clientSocket = serverSocket.accept();
    // start a new thread, passing it the clientSocket as an argument
}

Other possibly useful links: https://developer.android.com/resources/articles/painless-threading.html https://developer.android.com/guide/topics/fundamentals/processes-and-threads.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...