我有一个用Java编写的TCP服务器和客户端。服务器可以向客户端发送命令,然后客户端将执行该命令,例如:向服务器发送图像。
我正在发送一个字节数组的数据,这是有效的。
但是让我们想象一下,我想分别发送一个图像和一个文件。服务器如何知道哪个字节数组是正确的?或者,如果我想制作一个VoiceChat (需要连续发送字节数组)并单独发送图像?
这就是我的代码发送字节:
Client.java
public void writeBytes(byte[] bytes, Socket socket) throws IOException {
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.write(bytes);
out.flush();
}这是我接收它们并将其转换为图像的代码:
Server.java
public BufferedImage writeScreenshot(Socket socket, int length) throws IOException {
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte[] buffer = new byte[length];
in.readFully(buffer);
return ImageIO.read(new ByteArrayInputStream(buffer));
}发布于 2020-04-10 20:30:11
您需要设计一个"protocol" for the communication。协议定义了可以交换的消息以及它们在较低级别的数据流中的表示方式。
一种快速简单的协议是,首先发送要发送的数据的长度,然后发送数据:
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeInt(bytes.length);
out.write(bytes);
out.flush();接收器现在必须读取长度字段:
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
int length = in.readInt()
byte[] buffer = new byte[length];
in.readFully(buffer);当你使用像语音聊天这样的应用时,协议必须变得更加复杂。每条消息都必须有元数据,比如它包含的数据类型:图像、语音或其他数据。此外,您可能不希望从头开始设计此协议,而是使用已经存在的东西-例如real-time streaming protocol (RTSP)。
https://stackoverflow.com/questions/61140171
复制相似问题