I’m using just normal DataInputStream and DataOutputStream in threads for receive, send (with accept on server) to make a game, but it is really slow. >5 seconds lag.
Here is how I made it (most of it looks like that):
(dos is DataOutputStream)
dos = new DataOutputStream(socket.getOutputStream());
dos.writeFloat(dp.x);
dos = new DataOutputStream(socket.getOutputStream());
dos.writeFloat(dp.y);
dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(dp.username);
And for Input (this one is in server) I use:
(dis is DataInputStream, it’s in a for loop so i is for each player)
dis = new DataInputStream(list_sockets.get(i).getInputStream());
x = dis.readFloat();
dis = new DataInputStream(list_sockets.get(i).getInputStream());
y = dis.readFloat();
dis = new DataInputStream(list_sockets.get(i).getInputStream());
username = dis.readUTF();
So it is really slow, but I don’t know why 🙁
Please help?
EDIT: Every operation (send, accept, receive) has it’s own daemon thread.
Repeatedly creating
DataOutputStreamandDataInputStreaminstances is not good for performance.However, I suspect that a more important performance issue is that you are reading and writing without any Java-side buffering. This means that each read / write call is making one (and possibly many) syscalls to read data. System calls are a couple of orders of magnitude slower than ordinary Java method calls.
You need to wrap the Socket input stream in a
BufferedInputStreamand the output stream in aBufferedOutputStream, and then wrap these in the Data streams. (Note that when you do this, it becomes more important that youflushtheDataOutputStreamat the end of each message, or series of messages.Like I said above, you flush at the end of each message, or each sequence of messages. Each flush on your buffered output stream will result in a syscall, assuming there is data in the buffer to be flushed. If you flush on every write you are (probably) doing unnecessary syscalls.
It is up to you to figure out where your protocol’s message boundaries ought to be. It depends entirely on the details of the data you are sending / receiving, and the way it is processed.