简体   繁体   English

读写Java中的TCP socket

[英]Read and write to TCP socket in Java

I am creating a simple TCP server in java which accepts clients.我正在接受客户端的 java 中创建一个简单的 TCP 服务器。 Each client that connects to the server sends a message, and sends an answer based on the message.每个连接到服务器的客户端都会发送一条消息,并根据该消息发送一个答案。

In order to accept clients I am using ServerSocket class.为了接受客户,我正在使用ServerSocket class。 In order to read the client's message and write to him I am allowed to use only in the Socket , DataOutputStream and DataInputStream classes and in StandardCharsets.UTF_8 .为了读取客户端的消息并写信给他,我只能在SocketDataOutputStreamDataInputStream类以及StandardCharsets.UTF_8中使用。 In addition, every message that the server gets and sends must be in UTF-8 encoding.此外,服务器获取和发送的每条消息都必须采用 UTF-8 编码。

However, I am not sure how to read and write messages in UTF-8 encoding using those classes.但是,我不确定如何使用这些类以 UTF-8 编码读写消息。 The size of the messages is unbounded.消息的大小是无限的。 I tried to read about the read function of DataInputStream class, but I couldn't understand how to use it (if this indeed the function I need to use).我试图阅读有关DataInputStream class 的read function 的信息,但我不明白如何使用它(如果这确实是我需要使用的 function)。

DataOutputStream has a writeUTF() method, and DataInputStream has a readUTF() method. DataOutputStream有一个writeUTF()方法, DataInputStream有一个readUTF()方法。 Just note that these methods deal in modified UTF-8 rather than standard UTF-8, and they limit the UTF-8 data to 65535 bytes max.请注意,这些方法处理修改后的 UTF-8而不是标准的 UTF-8,并且它们将 UTF-8 数据限制为最大 65535 字节。

It would be better to handle the UTF-8 yourself manually.最好自己手动处理 UTF-8。

The sender can use String.getBytes() to encode a String to a byte[] array using StandardCharsets.UTF_8 , then send the array's length using DataOutputStream.writeInt() , and then finally send the actual bytes using DataOutputStream.write(byte[]) .发送方可以使用String.getBytes()使用StandardCharsets.UTF_8String编码为byte[]数组,然后使用DataOutputStream.writeInt()发送数组的长度,最后使用DataOutputStream.write(byte[])

The receiver can then read the array length using DataInputStream.readInt() , then allocate a byte[] array and read it using DataInputStream.readFully() , and then finally use the String constructor to decode the bytes using StandardCharsets.UTF_8 .然后接收者可以使用DataInputStream.readInt()读取数组长度,然后分配一个byte[]数组并使用DataInputStream.readFully()读取它,最后使用String构造函数使用StandardCharsets.UTF_8解码字节。

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

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