通过Java中的套接字损坏字符串

时间:2012-11-02 20:04:05

标签: java java-ee

我有一个问题是通过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”变量被转移,并在客户端中被破坏。

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

2 个答案:

答案 0 :(得分:1)

isUserNameboolean。也许你的意思是socketWriter.println(userName);

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

System.out.println(userNameResultParameter);
System.out.print("Chars:");
for (char c : userNameResultParameter.toCharArray())
    System.out.print(" 0x" + Integer.toHexString((int)c));

答案 1 :(得分:0)

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

尝试像这样构建InputStreamReader

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