所以我有一个java服务器和客户端,数据被很好地发送到服务器并且服务器正在对其进行交互,但是我发现客户端需要很长时间才能响应服务器发送的内容,经过一段时间我发现我的服务器发送给客户端的数据比应该发送的数据长得多。
发送给客户端的数据包包含我发送的所有数据,但是它后面也有很多空白,我想解决这个问题,有人有什么想法吗?
我获取数据的代码是服务器上每个客户端的简单 for 循环,这会将客户端数据添加到字符串中,然后将该字符串添加到数据包中:
类播放器列表
public static String getString()
{
String message = "";
for(int x = 0; x < list.size(); x++)
{
Player player = list.get(x);
if(message.equals(""))
{
message += player.name+";"+player.address+";"+player.pos[0]+";"+player.pos[1]+";"+player.fakeRotation+";"+player.rotation+";"+player.rotationSpeed+";"+player.speed+";"+player.sheildEnabled+";"+player.sheildStrength+";"+player.health;
}
else
{
message += ","+player.name+";"+player.address+";"+player.pos[0]+";"+player.pos[1]+";"+player.fakeRotation+";"+player.rotation+";"+player.rotationSpeed+";"+player.speed+";"+player.sheildEnabled+";"+player.sheildStrength+";"+player.health;
}
}
System.out.println(message);
return message;
}
类发送
while(Server.serverRunning)
{
for(int p = 0; p < PlayerList.list.size(); p++)
{
Player player = PlayerList.list.get(p);
try
{
byte[] buf = PlayerList.getString().getBytes();
//send the message to the client to the given address and port
packet = new DatagramPacket(buf, buf.length, player.address);
Server.socket.send(packet);
}
catch (IOException e)
{
System.out.println("Can't send packet to player: "+player.name);
}
}
}
我知道从 getString 方法收到的数据是正确的,并且没有空格,因为我已经对其进行了测试,因此当我将字符串添加到数据包时一定会发生这种情况。
预期数据在输出中显示为:
Luke;127.0.0.1:63090;50.0;50.0;0.0;0.0;0.0;0.0;true;100;100
但是实际数据在客户端上显示为:
Luke;127.0.0.1:63090;50.0;50.0;0.0;0.0;0.0;0.0;true;100;100 (lots of spaces here) ...line is too long, please switch to wrapped mode to see whole line...
接收数据的客户端代码是:
receiveData = new byte[clientSocket.getReceiveBufferSize()];
receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
receiveMessage = new String(receivePacket.getData());