我的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
每个字符接收后的空字符对我来说有些奇怪。让我无法将字符串与存储在服务器中的内容进行比较。 那些空字符是什么,它们来自哪里。
最佳答案
您写的是字符,但读的是行的字节。那行不通的。如果要写入字符,则需要使用完全相同的编码来读取字符。如果要写入字节,则需要读取字节。在字节级别精确指定您的协议(protocol),并在客户端和服务器中遵循规范。
参见 this question获取更多信息。
关于java - BufferedReader 在与 TCP 套接字一起使用时在字符串中提供更多空字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18887719/