What is the best way to send a se开发者_StackOverflowries of data (float array) from a server to a client continuously through Java socket? For example, I have a server that produces float data every 1ms, and I would like to send this data to a client. My plan is to put this process in a thread (server side) and send it to the client continuously. Is it possible to achieve this through Java socket? or should I write the data into a file first before sending it to the client?
Thanks!
There should be no problem doing this via socket. Basically you set up a thread on the server side to send data whenever a new set is provided.
Then on the client side, set up a thread who constantly listens on the socket, reads in and unpacks the data whenever available, post it somewhere for the processing code of your client to use it and then go back to a poll/sleep cycle until the server sends more data.
Just make sure on the client side you provide a method kill the listener thread if the socket closes (Server shuts down, network hickup, etc).
Using simple socket programming, this is not a problem at all:
- Open a TCP connection between server and client
- Send the data using the connections
InputStream
andOutputStream
- Close the connection in case of any error/disconnection
Note that this solution is not very scalable, and if this needs to be scaled you will need to use non-blocking IO (so that your server does not choke on all the open connections and the running threads)
As long as the client keeps a connection open you can send the data.
If you are using http then the connection is closed after each request, unless you use something like Comet. You can look on wikipedia, but this article may be helpful from a java POV: http://www.javaworld.com/javaworld/jw-03-2008/jw-03-asynchhttp-test.html
Update If you are using a regular socket-based server and a client that is set up to have a constant connection, you are free to send the data whenever you want, as long as the connection is open. It will only be closed by those connected, or a network problem.
But, if you are using http then the rules change a bit, which is what the second paragraph is for.
The easiest way would be to use a ObjectInputStream/ObjectOutputStream on client/server side, and then the client trying a read from the stream. If there is no new data the client waits, and as soon as the server sends a new array the client reads it, processes it, and starts waiting again. Depending on what the client does it may be sensible to put the reading into an extra thread that hands the array of to the actual processing method.
精彩评论