【问题标题】:BufferedReader give more null character in string while using with TCP SocketBufferedReader 在与 TCP Socket 一起使用时在字符串中提供更多空字符
【发布时间】:2013-09-19 06:37:32
【问题描述】:

我的 TCP Server 是这样的。

import java.net.*;
import java.io.*;
public class NetTCPServer {
public static void main(String[] args) throws Exception{

ServerSocket sock;
sock = new ServerSocket(1122);
if(sock == null)
    System.out.println("Server binding failed.");
System.out.println("Server is Ready ..");

do{
    System.out.println("Waiting for Next client.");
    Socket clientSocket = sock.accept();
    if(clientSocket!=null)
        System.out.println("Clinet accepted. "+sock.getInetAddress().getHostAddress());

    DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
    //DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    String name;
    String pass;
    String line;
    name = in.readLine();
    pass = in.readLine();
    for(int i=0;i<name.length();i++)
        System.out.print(name.charAt(i)+","); //see more null char are receiving here

        System.out.println("");
        System.out.println(name +"  "+ name.length()+"  \n" + pass+"  "+pass.length());
    }while(true);

}
}

各自的TCP Client如下。

import java.net.*;
import java.io.*;
public class NetTCPClient {

    public static void main(String[] args) throws Exception {
        InetAddress addr = InetAddress.getByName("localhost");

        Socket sock;
        sock = new Socket(addr,1122);
        if(sock == null)
            System.out.println("Server Connection failed.");
        System.out.println("Waiting for some data...");
        DataInputStream input = new DataInputStream(sock.getInputStream());
        DataOutputStream output = new DataOutputStream(sock.getOutputStream());
        String uname="ram";
        String pass="pass";
        output.writeChars(uname+"\n");// \n is appended just make to readline of server get line
        output.writeChars(pass+"\n");
        }

}

当我编译两者并启动服务器并在客户端运行后,我得到以下输出。

Server is Ready ..
Waiting for Next client.
Clinet accepted. 0.0.0.0
,r,,a,,m,,
ram7  pass9

每个字符接收后的空字符对我来说有点奇怪。使我无法将字符串与存储在服务器中的内容进行比较。 这些空字符是什么,它们来自哪里。

【问题讨论】:

标签: java sockets tcp


【解决方案1】:

你写字符,但读 字节。那是行不通的。如果要写入字符,则需要使用完全相同的编码读取字符。如果要写入字节,则需要读取字节。在 byte 级别精确指定您的协议,并遵循客户端和服务器中的规范。

更多信息请参见this question

【讨论】:

  • @BishnuBidari 否。但是,您的发送者和接收者必须准确地就将发送哪些字节达成一致。
猜你喜欢
  • 1970-01-01
  • 2016-12-21
  • 2013-05-31
  • 1970-01-01
  • 2015-06-11
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多