3

我在通过 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”变量被传输并在客户端中被破坏。

你能帮忙解决这个问题吗?谢谢!

4

2 回答 2

1

isUserName是一个boolean。也许你的意思是socketWriter.println(userName);

请使用下面的代码向我们展示损坏的字符串是什么样的!

System.out.println(userNameResultParameter);
System.out.print("Chars:");
for (char c : userNameResultParameter.toCharArray())
    System.out.print(" 0x" + Integer.toHexString((int)c));
于 2012-11-02T20:52:03.540 回答
0

我认为,问题在于InputStreamReader. 默认情况下,读者假设传入字符数据的编码是您平台的默认编码,但是Writer(在服务器端)发送的是 UTF-8 数据。

尝试构建InputStreamReader这样的:

new InputStreamReader(socket.getInputStream(), "UTF-8")

于 2012-11-03T01:00:23.703 回答