我在通过 Java 中的套接字传输字符串时遇到问题。当我尝试从服务器接收数据时,数据已成功传输,但已损坏。我不知道出了什么问题。
这是客户端的代码:
public String getUserNameServerResult(String userNameParameter) {
Socket socket;
BufferedReader socketReader;
PrintWriter socketWriter;
String userNameResultParameter = null;
try {
socket = new Socket(HOST_NAME, PORT_NUMBER);
socket.setSoTimeout(SERVER_REQUEST_TIMEOUT);
socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
socketWriter = new PrintWriter(socket.getOutputStream());
socketWriter.println(numberRequest);
socketWriter.flush();
socketWriter.println(userNameParameter);
socketWriter.flush();
userNameResultParameter = socketReader.readLine();
socketReader.close();
socketWriter.close();
socket.close();
System.out.println(userNameResultParameter);
} catch(IOException ioEx) {
ioEx.printStackTrace();
}
return userNameResultParameter;
}
readLine() 方法中的读取行传输了损坏的字符串。
这是服务器的一段代码:
public synchronized void run(){
System.out.println(new Date().toString()+" :\nAccepted client: "
+socket.getInetAddress()+":"+socket.getPort()+"\n");
try {
while(!isInterrupted()) {
String numberRequest = socketReader.readLine();
if(numberRequest == null) {
break;
}
switch(numberRequest) {
case "1": // Determines if the user name exists in the Database.
String userName = socketReader.readLine();
boolean isUserName = ServerRequest.isUserNameExists(userName);
socketWriter.println(isUserName);
socketWriter.flush();
break;
default: break;
}
}
} catch(IOException ex) {
System.err.println(ex.getMessage());
}
}
“isUserName”变量被传输并在客户端中被破坏。
你能帮忙解决这个问题吗?谢谢!