简体   繁体   English

java线程套接字:哪个线程接收数据包?

[英]java threaded socket : which thread receives the packet?

I am working on a p2p project. 我正在做一个p2p项目。 This project is supposed to be able to send and receive binary files and text messages concurrently. 该项目应该能够同时发送和接收二进制文件和文本消息。 I have two separate threads for receiving file and messages. 我有两个单独的线程用于接收文件和消息。 The problem is how to specify which thread should receive packet that is coming. 问题是如何指定哪个线程应该接收即将到来的数据包。 now is it better to have just one thread for both operations? 现在最好只为两个操作使用一个线程? If yes how can i recognize the received packet type? 如果是,我如何识别接收到的数据包类型?

You need one thread to manage the socket, and one each for chat and file transfer. 您需要一个线程来管理套接字,每个线程用于聊天和文件传输。 The thread manager decided who gets the packet, based on whatever protocol you devise to distinguish the packets. 线程管理器根据您设计的区分包的协议决定谁获取包。

You will need a custom packet to determine what kind 'packet' it is. 您将需要一个自定义数据包来确定它是哪种“数据包”。 For example, a serialized class that implements an interface that knows what type of packet it is. 例如,一个实现了一个接口的序列化类,该接口知道它是什么类型的数据包。 Rough structure example. 粗糙的结构示例。

Packet implements Serializable{
 enum type;
 Object data

 public setdata
 public getdata
 ...
 ...
}

There is two ways to do this. 有两种方法可以做到这一点。

1 - Do what you suggested. 1-做您建议的事情。 Use one thread to handle both files and messages depending on the type of packet. 使用一个线程来处理文件和消息,具体取决于数据包的类型。

2 - Use two seperate threads. 2-使用两个单独的线程。 But create a handler to deliver the packet to give to the proper thread depending on the packet type. 但是创建一个处理程序来传递数据包,以根据数据包类型将其提供给适当的线程。

edit: 编辑:

Oh as Jim mentioned, you'll need another thread to manage the socket. 就像Jim提到的,您需要另一个线程来管理套接字。

I have two separate threads for receiving file and messages. 我有两个单独的线程用于接收文件和消息。

Why? 为什么?

The problem is how to specify which thread should receive packet that is coming. 问题是如何指定哪个线程应该接收即将到来的数据包。

Your first problem is that there are no 'packets' in the TCP API. 您的第一个问题是TCP API中没有“数据包”。 It provides a bytestream. 它提供了一个字节流。 Any packetising is entirely up to you at both ends. 任何打包都完全取决于您的两端。

Your second problem is that the thread that entered read() first will get the next data that arrives (or has already arrived). 您的第二个问题是,首先输入read()的线程将获得下一个到达的(或已经到达的)数据。

now is it better to have just one thread for both operations? 现在最好只为两个操作使用一个线程?

Definitely. 当然。

If yes how can I recognize the received packet type? 如果是,如何识别接收到的数据包类型?

As I said above, if there are to be 'packets' in this application, you will have to define them. 如前所述,如果此应用程序中有“数据包”,则必须定义它们。 That will almost certainly include a length word and it may as well include a type word as well. 几乎可以肯定,这将包括一个长度词,也可能包括一个类型词。

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

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