通过telnet.exe与Java服务器套接字通信
我正在编写一个简单的服务器,用于试验服务器套接字和通过telnet.exe与Java服务器套接字通信,java,sockets,telnet,Java,Sockets,Telnet,我正在编写一个简单的服务器,用于试验服务器套接字和telnet.exe public static void main(String[] args) throws IOException { String line; ServerSocket ss = new ServerSocket(5555); Socket socket = ss.accept(); System.out.println("Waiting for a client..."); Inp
telnet.exe
public static void main(String[] args) throws IOException {
String line;
ServerSocket ss = new ServerSocket(5555);
Socket socket = ss.accept();
System.out.println("Waiting for a client...");
InputStream sin = socket.getInputStream();
OutputStream sout = socket.getOutputStream();
DataInputStream in = new DataInputStream(sin);
DataOutputStream out = new DataOutputStream(sout);
out.writeUTF("\u001B[2J");
out.writeUTF("Hello client\r\n");
line = in.readUTF();
System.out.println("The dumb client just sent me this line : " + line);
System.out.println("I'm sending it back...");
out.writeUTF(line);
out.flush();
System.out.println("Waiting for the next line...");
System.out.println();
}
现在我正在运行这个服务器,并通过telnet.exe与他连接。没关系。但当我向服务器发送消息时,我不会收到此消息:
为什么它不工作?telnet客户端用换行符终止每个输入行。但是DataInputStream不会将其识别为输入字符串的终止符,因为DataInputStream用于二进制数据
BufferedReader inputReader = new BufferedReader(new InputStreamReader(in));
[...]
line = inputReader.readLine();
对于以换行符结尾的消息返回到客户端的基于文本的输出,应使用BufferedReader的输出模拟,即。数据输入用于读取二进制文件 来自Javadoc for readUTF() 读取使用修改的UTF-8格式编码的字符串。readUTF的一般约定是,它读取以修改的UTF-8格式编码的Unicode字符串的表示形式;然后将该字符串作为字符串返回 首先,读取两个字节,并使用它们以readUnsignedShort方法的方式构造一个无符号16位整数。此整数值称为UTF长度,并指定要读取的附加字节数。然后,通过分组将这些字节转换为字符。每个组的长度由组的第一个字节的值计算得出。组后面的字节(如果有)是下一组的第一个字节 这意味着前两个字节必须具有以下UTF字符串的二进制长度 您在前两个字节中键入了类似于
k
和j
的内容,因此长度大约为25000字节,也就是说,您没有键入那么多,这就是它没有返回的原因
相反,您希望能够使用BufferedReader和PrintWriter之类的类来读/写文本