Reputation: 3553
I'm trying to communicate through sockets using TCP. The data that needs to be sent is a drawing, whilst it is being drawn. So the option would be to send all the points, or only shapes (series of points).
Since it would be nice to have it being drawn instantly, sending points seems better. It's only for local use, so a lot of data shouldn't be an issue. Now the issue I'm having is understanding how exactly the socket works. Currently my code is as follows:
while(true){
try {
Thread.sleep(10);
}
catch (InterruptedException e) {}
switch(connectionStatus){
case CONNECTED:
if(isHost){
try {
oos.writeObject(myObject);
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
myObject = (myObjectType) ois.readObject();
mainFrame.repaint();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
But needless to say, this seems rather inefficiënt as it's running constantly. Is there a way to only write to the ObjectOutputStream
(oos) when new data is there? I guess to read you have to poll though. Does reading also clear the ObjectOutputStream?
Edit
To be clear: I want to send multiple Point
-objects through a socket. So every time a Point
gets added to eg the server, it should send this point to the client.
Now, what do I need to put inside the oos.writeObject()
? The single Point
, or a List
of Point
s? And how are they retrieved from the ois.readObject()
?
I'm a bit confused, because the writing to the ObjectOutputStream could be fast or slow. Se reading the ObjectInputStream - the way I see it - would or cause a big delay (if it reads a value every ~15ms and points get added faster than that) or cause lots of lag.
Upvotes: 1
Views: 302
Reputation: 2281
I wrote a library (which you can find on maven) that will take away some the complexity of implementing threading and synchronization yourself:
https://github.com/xtrinch/socket-live
Consists of three main components (which later result into three running threads):
SocketConnection.java: main thread, run by the user of the library, which makes sure the connection is always open
SocketRead.java: read thread which continuously attempts to read incoming messages if any
SocketWrite.java: write thread which writes any messages in write queue to socket
You also have the option to disable the read thread, if you don't need it.
Library will make sure the connection stays open at all times, reconnect upon being closed, and it's been battle tested :)
Upvotes: 0
Reputation: 1788
Upvotes: 0
Reputation: 16736
Is there a way to only write to the
ObjectOutputStream
(oos
) when new data is there?
Yes. Whenever the user draws something, push data down the ObjectInputStream
.
I guess to read you have to poll though.
That is incorrect. Typically, reading from an open stream is a blocking operation: if you attempt to read something and there's nothing there, the read
method will simply block until new data is available.
Upvotes: 1