Send message from a basic server to a specific client

前端 未结 1 1172
礼貌的吻别
礼貌的吻别 2020-12-10 20:25

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

1条回答
  •  时光说笑
    2020-12-10 20:57

    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

    0 讨论(0)
提交回复
热议问题