简体   繁体   English

我可以在单线程中使用两个套接字吗?

[英]Can I use two sockets in single thread?

I am having trouble developing a chat application including file sharing.我在开发包括文件共享在内的聊天应用程序时遇到问题。 It's a server and client based desktop application.它是一个基于服务器和客户端的桌面应用程序。 I am able to develop chat and also file sharing individually.我能够单独开发聊天和文件共享。

Now I want merge two project and having problem.现在我想合并两个项目并且遇到问题。 Is it possible to use multiple socket in single thread like main thread?是否可以像主线程一样在单线程中使用多个套接字? Or do I have to use one for chatting and another for file sharing?或者我必须使用一个用于聊天,另一个用于文件共享?

I think that is possible but in the same thread one operation with one socket have to wait all the operations from annother finish. 我认为这是可行的,但在同一线程中,一个套接字的一项操作必须等待另一项操作完成。 if you want the two operations execute at the same time do it in different threads. 如果要同时执行这两个操作,请在不同的线程中执行。 Hope that helps :) 希望有帮助:)

Yes it is possible for a single thread to use multiple sockets.是的,单个线程可以使用多个套接字。 See the Selector API.请参阅Selector API。

The basic idea is that the code in your thread needs to know about all of the selectable channels (sockets, open files, etc) that it needs to read from or write to.基本思想是线程中的代码需要知道它需要读取或写入的所有可选通道(套接字、打开的文件等)。 It registers the channels with the selector.它向选择器注册通道。 Then you make a select call which will (for example) block until one of the registered channels is ready;然后您进行一个select调用,该调用将(例如)阻塞,直到注册的通道之一准备就绪; eg which socket has data that can be read now ... without blocking.例如,哪个套接字具有现在可以读取的数据......没有阻塞。

It is complicated, but rather than explaining it all here, I suggest that you read Baeldung's Introduction to the Java NIO Selector which includes an example.它很复杂,但与其在这里解释一切,我建议您阅读 Baeldung 的Java NIO 选择器简介,其中包含一个示例。

But the bottom line is that using Selector will probably entail significant restructuring of your existing code.但最重要的是,使用Selector可能需要对现有代码进行重大重组。 And if your code is using (for example) a 3rd-party library to do the I/O, then this approach probably won't work.如果您的代码使用(例如)第 3 方库来执行 I/O,那么这种方法可能不起作用。 Using multiple threads may well be a simpler option.使用多线程可能是一个更简单的选择。

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

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