![](/img/trans.png)
[英]TCP socket: Why BufferedReader.readLine() get NULL?
[英]BufferedReader give more null character in string while using with TCP Socket
我的TCP服務器就是這樣。
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
每個字符接收后的空字符對我來說有點奇怪。 使我無法將字符串與服務器中存儲的內容進行比較。 這些空字符是什么,它們從何而來。
您寫入字符,但讀取字節 行 。 那行不通。 如果要編寫字符,則需要以完全相同的編碼讀取字符。 如果要寫入字節,則需要讀取字節。 精確地在字節級別指定協議,並在客戶端和服務器中均遵循規范。
有關更多信息,請參見此問題 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.