简体   繁体   中英

Send message from a basic server to a specific client

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM