Constantly sending data over Java socket

What is the best way to send a series of data (float array) from server to client continuously over Java socket? For example, I have a server that produces floating point data every 1ms, and I would like to send this data to the client. My plan is to put this process on a thread (server side) and send it to the client continuously. Is it possible to achieve this over Java socket? or should I write the data to the file first before sending it to the client?

Thank!

+2


source to share


4 answers


There is no way to do this over a socket. Basically you set up a server side stream to send data whenever a new set is provided.

Then, on the client side, set up a thread that constantly listens on the socket, reads and decompresses the data whenever it is available, put it somewhere for your client's processing code to use it, and then fall back to polling / sleep loop until the server will send more data.



Just make sure on the client side you provide a method to kill the listener thread if the socket is closed (server shuts down, network hickup, etc.).

+5


source


With simple socket programming, this is not a problem:

  • Open TCP connection between server and client
  • Send data using connections InputStream

    andOutputStream

  • Close connection in case of any error / disconnection


Please note that this solution is not very scalable and if it needs to scale you will need to use non-blocking IO (so your server doesn't choke off all open connections and current threads)

+3


source


As long as the client keeps the connection open, you can send data.

If you are using http then the connection will be closed after every request unless you are using something like Comet. You can look at wikipedia, but this article might be helpful from java POV: http://www.javaworld.com/javaworld/jw-03-2008/jw-03-asynchhttp-test.html

Refresh . If you are using a regular socket-based server and a client configured for a persistent connection, you can send this data whenever you want, as long as the connection is open. It will only be closed by connected or network problems.

But, if you are using http, then the rules change slightly, which is for the second paragraph.

+1


source


The easiest way is to use ObjectInputStream / ObjectOutputStream on the client / server side and then the client tries to read from the stream. If the client does not expect new data, and as soon as the server sends a new array, the client will read it, process it, and start again. Depending on what the client is doing, it might be wise to put the read on an additional thread that passes the array to the actual processing method.

0


source







All Articles