简体   繁体   English

Java服务器-如何从InputStreamReader获取输入并将其转换为String?

[英]Java Server - How to take input from InputStreamReader and convert to a String?

I'm trying to get a very simple Client-Server system to work, where the Client will send a String over to the Server , and the server will then store that String into a file. 我正在尝试使一个非常简单的Client-Server系统正常工作,其中Client将向Server发送String,然后server会将该String存储到文件中。

The client sends the string through: 客户端通过以下方式发送字符串:

//Other Code

sockStrm = new DataOutputStream (clientSocket.getOutputStream ());

//Other code

sockStrm.writeChars (line);

//Other code

And the Server receives the String with: 服务器收到带有以下内容的字符串:

//Other code 

strm = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ())); 

//Other code

stringLine = strm.readLine (); 

//Other code

When I send the string STOP , the length of the String is 4 on the client side, and on the server side the length of the String is 9 and displays as STOP 当我发送字符串STOP ,客户端的字符串长度为4,而在服务器端,字符串的长度为9并显示为STOP

I've tried to substring the received String on the Server side, without luck. 我试图在服务器端对接收到的字符串进行子字符串化,但是没有运气。

Any pointers on how to deal with this? 有关如何处理此问题的任何指示?

Use symmetric methods: 使用对称方法:

DataOutputStream sockStrm =...
sockStrm.writeUTF(str);

and

DataInputStream sockStrm = ...
String str = sockStrm.readUTF();

writeChars writes individual characters as two byte values. writeChars将单个字符写为两个字节值。 Readers follow the encoding to reconstruct the string from a sequence of bytes, which will definitely not be according to high-byte-low-byte for each character code. 读者遵循编码来从字节序列中重建字符串,对于每个字符代码,绝对不会按照高字节-低字节进行操作。 Hence you get some mish-mash of zero bytes with the original low-byte values so you still have a glimpse of the original string value. 因此,您会得到零字节的杂乱混搭和原始的低字节值,因此您仍然可以一窥原始的字符串值。 Using \\x00 to denote a NULL byte: 使用\\ x00表示NULL字节:

S-T-O-P => on the line: \x00-S-\x00-T-\x00-O-\x00-P => prints as STOP

Use a loop over the characters of the incoming string and display their integer values (str.charAt(i)) to see the above for yourself. 在传入字符串的字符上使用循环,并显示它们的整数值(str.charAt(i)),自己看看上面的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM