因此,我有一個java服務器和客戶端,數據正在發送到服務器罰款和服務器是interperating它,但我發現客戶需要很長時間來響應服務器發送它,一段時間後環顧四周我發現我的服務器發送客戶端的數據比應該發送的數據長。爲什麼這個Java UDP數據包長度太長?
發送給客戶端的數據包含有我發送的所有數據,但它後面也有大量空白,我想解決這個問題,任何人有任何想法?
我的代碼來獲取數據是一個簡單的服務器上的每個客戶端的循環,這增加了客戶端數據到一個字符串,該字符串被添加到包:
類PlayerList
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());
我想,那是因爲你正試圖創建buf.length的大小,但你的數據報只發送player.address。所以,剩餘的空間充滿了空間。 – kosa
您沒有顯示接收數據包的* client *代碼。 –
數據包末尾有空白還是有\ 0 s?它可能會用空值填充到默認數據包大小。 – Tremmors