我正在使用java/libgdx,並且遇到套接字問題。它工作緩慢。我的小遊戲呈現出左右移動的角色。通過tcp/localhost發送後,它移動得更慢。我從客戶端和服務器類添加兩段代碼。請幫幫我。我被困住了。提前致謝。如果有必要,我會把整個代碼。套接字工作太慢:: java/libgdx
// 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();
}
}
//服務器
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();
}
}
如果你想要編寫字符串,你最好使用DataOutputStream和[writeUTF()](https://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html#writeUTF( java.lang.String中))。並且不要忘記清空書面數據。 – Robert