0

I have an Android app that needs to let multiple socket communication. here is the basic work around:

My application( Say Server) is a service which will run as a sever socket. other application can connect to it on predefined port. There can be a multiple connection say client 1, client 2.

So when client 1 send hello, server will process this and should send reply back to client 1.

Currently I am able to connect server for client 1 and client 2. I have created input , output buffer for same. But I am not sure how server will detect from which it has received "hello".

I was referring this example , but still not clear how to use that solution:

How can I handle multiple clients connected to a server using sockets?

Community
  • 1
  • 1
morya
  • 835
  • 2
  • 10
  • 19

2 Answers2

0

The ServerSocket.accept() call, which creates a connection on the server side, returns a socket. Each call to accept will create a new Socket for communication with that particular client. So whatever Socket sends you input is the Socket that needs a response.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Thats correct but how to detect which output should be used to response back. – morya Jun 18 '14 at 15:43
  • If you mean which OutputStream, the OutputStream associated with the socket. If you mean something else, you need to be more clear. – Gabe Sechan Jun 18 '14 at 16:46
  • I created android app which can communicate using socket. I can connect to same through command prompt (for testing) using telnet. When One to One communication is going it works fine. but if I open another command prompt, I am able to connect and communicated. But when I tried to send request from first the response is received on second. Actually it should response back to sender that first prompt. I have created thread the same way way explain in link as mentione in first post. But not sure how to detect which out put stream to be used to send response back. – morya Jun 18 '14 at 17:14
0

First I tried to check thread ID whenever A new connection is established, but it was same as it is Server Id. Whenever the request received from a specific thread it has a ID. you will get it by

Thread.currentThread().getId();

This is unique for each client. So I save this and use this to detect to which thread I should reply back.

Thanks all for your support.

morya
  • 835
  • 2
  • 10
  • 19