我試圖通過比較在服務器端的消息接收計數器與客戶端上維護的消息發送計數器來跨TCP連接測試數據包丟失。我發送的消息是25千字節,前5個字節包含來自客戶端的計數,字符串形式爲長度爲5個字節的字符串。但是,在3或4個成功消息之後,服務器無法找到計數。有什麼我忘記考慮?我的猜測是,服務器無法跟上客戶端,因爲錯誤發生之前成功消息的數量從3到4不等。嘗試在java中通過tcp發送kilobyte消息時出錯
客戶端代碼:
try{
clientSocket = new Socket("192.168.0.15", SERVER_PORT);
DataInputStream in = new DataInputStream(clientSocket.getInputStream());
DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
int messageCounter = 0;
byte [] message1 = new byte[25 * 1024];
byte [] returnMessage1 = new byte[25 * 1024];
byte [] count;
long startTime1 = System.nanoTime();
while (messageCounter < 100000) {
System.out.println(messageCounter);
addCountToMessage(formatCount(messageCounter).getBytes(), message1);
out.write(message1);
in.read(returnMessage1);
messageCounter ++;
}
}
SERVER端代碼:
try {
byte [] data = new byte[35 * 1024];
System.out.println("STARTING LOOP");
System.out.println("***********************************");
int messageCounter = 0;
int clientMessageCount = 0;
String clientCountString = "";
byte[] clientCount = new byte[5];
while (true){
in.read(data);
clientCount[0] = data[0];
clientCount[1] = data[1];
clientCount[2] = data[2];
clientCount[3] = data[3];
clientCount[4] = data[4];
clientCountString = new String(clientCount);
System.out.println("Received Count String: \"" + clientCountString + "\"");
clientCountString = clientCountString.replace("*", "");
clientMessageCount = Integer.parseInt(clientCountString);
System.out.println("Client Count: " + clientMessageCount + ", Server Count: " + messageCounter);
out.write(data);
System.out.println("***********************************");
messageCounter ++;
}
}
OUTPUT服務器:
java TCPServer
STARTING LOOP
收到的計字符串: 「0 ****」 客戶數:0,服務器的數量:0
收到的計字符串: 「1 ****」 客戶端數量:1,服務器數量: 1
收到的計字符串: 「2 ****」 客戶端計數:2,服務器計數:2
收到的計字符串:「 3 ****」 客戶端數量:3,服務器的數量:3
收到的計字符串: 「」
Exception in thread "Thread-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at Connection.run(TCPServer.java:52)