Cenarius Cenarius - 6 months ago 58
Java Question

Socket works too slow :: java/libgdx

I am using java/libgdx and I have encountered problem with sockets. It works slow. My little game presents character, which move left and right. After sending by tcp/localhost, it moves slower. I add two pieces of codes from Client and Server class. Please help me. I stucked. Thanks in advance. If it is necessary I will put whole code.

//CLIENT

public class ClientThread extends Thread{

public void run(){

hints = new SocketHints();
hints.connectTimeout = 11000;

while(trwanie)
{
socket = Gdx.net.newClientSocket(Protocol.TCP, "localhost", 8784, hints );
if(!socket.isConnected() )
System.out.println("NIE JEST");
//System.out.println("socket null?");
if(socket!=null)
{
try {
socket.getOutputStream().write(new String("CZESC server").getBytes()); // wiadomosc wysylana
//byte[] read = new byte[1024];
socket.getInputStream().read(read); //odebrana od servera
readString = new String(read).trim();
XY = readString;
StringToFloat();

} catch (IOException e) {
e.printStackTrace();socket.dispose();
}
}
//socket.dispose();
if(Gdx.input.isKeyPressed(Keys.ESCAPE))
{
WylaczPentle();
System.out.println("Wychodzimy z pentli");
Gdx.app.exit();
}
}
socket.dispose();
}
}


//Server

public class ServerThread extends Thread{

public void run()
{
hints = new ServerSocketHints();
hints.acceptTimeout = 12000;
socketHints = new SocketHints();
while(trwanie)
{
server = Gdx.net.newServerSocket(Protocol.TCP, "localhost", 8784, hints);
socket = server.accept(socketHints);
if(socket != null)
{
//byte[] read = new byte[1024];
try {
socket.getInputStream().read(read);
socket.getOutputStream().write( (WspolzednaX+"/"+WspolzednaY).getBytes()); //---

} catch (IOException e) {
e.printStackTrace();
server.dispose();
}
}
server.dispose();
if(Gdx.input.isKeyPressed(Keys.ESCAPE))
{
WylaczPentle();
System.out.println("Wychodzimy z pentli");
Gdx.app.exit();
}
}
server.dispose();
}
}

Answer

One reason that your code is slow is that your client seems to be repeatedly opening / using / closing a socket to the same server. Considering that opening and closing takes a significant amount of time (to perform the network packet exchanges), you would do better opening the Socket once, and keeping it open while the client and server exchange multiple "messages".

There are other problems with your code. For example, the read(bytes[]) method returns an int that says how many bytes were actually read. Your client and server side code is ignoring that, and assuming that all read.length bytes in the buffer contain valid data.