Simonne
Simonne

Reputation: 1

Java socket parallel sending

I need to monitor device state from my Java app ( example device ip=192.168.0.22 and port 17000 , monitor mean that I send every 1 sec request and get data like response ). I need to parallel with that send to that device another messages and receive answers ( on same ip and same port ). I create socket=new Socket(ipAddress, port). How to achieve that I don't get colision ( I need : I send first, I get response from first, I send second I get response from second, I send third I get response from third and so on ) ?

Upvotes: 0

Views: 1332

Answers (3)

DaveJohnston
DaveJohnston

Reputation: 10161

You could define a request type identifier. Then in the SocketServer side of the implementation you could parse the identifier and pass the request to a new thread used to deal with that type of request. So in your case you would define 3 different handlers and each type you get a request you choose which handler to use to process the request. Each request would be made using the same Socket.

However, from your last sentence:

I need : I send first, I get response from first, I send second I get response from second, I send third I get response from third and so on

This doesn't sound like parallel requests. Rather it sounds like you want to run them one after the other, i.e. the second request depends on the response of the first request?? If this is the case then you just use the same socket (don't create a new one for each request). Then the logic in the request code would simply be send request 1, wait for response 1, then send request 2 etc. etc.

Upvotes: 1

liunx
liunx

Reputation: 761

If your work is care about the order, so you have to send the request data one by one, in my understand that you mean you will get colision when you send a data to the device at the same time, the device reply to you? do not worry, because the socket have to buffer, one for send and another for recieve.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533870

Unless I am missing something,

  • you can do each in a seperate thread,
  • or you can send the request to all three sockets and wait for all three replies.
  • or you could design your server to have three pending requests at once. (It may work correctly already) Send three requests to one connection and wait for three replies.

The last one might be the most efficient solution.

Upvotes: 1

Related Questions