- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有一个简单的 TCP 服务器,它能够在一个端口上监听和接受多个连接。然后它不断等待从其连接中读取数据。为方便起见,它使用名为 ConnectedClient 的 TcpClient 包装类,并使用 ConnectedClients 列表(字典)来跟踪所有连接。它基本上是这样的:
/* this method waits to accept connections indefinitely until it receives
the signal from the GUI thread to stop. When a connection is accepted, it
adds the connection to the list and calls a method called ProcessClient,
which returns almost immediately.*/
public void waitForConnections() {
// this method has access to a TcpListener called listener that was started elsewhere
try {
while (!_abort) {
TcpClient socketClient = listener.AcceptTcpClient();
//Connected client constructor takes the TcpClient as well as a callback that it uses to print status messages to the GUI if
ConnectedClient client = new ConnectedClient(socketClient, onClientUpdate);
clients.Add(client.id, client);
ProcessClient(client);
}
}
catch (Exception e) {
onStatusUpdate("Exception Occurred: " + e.Message);
}
}
/* This method doesn't do much other than call BeginRead on the connection */
private void ProcessClient(ConnectedClient client) {
try {
// wrapper class contains an internal buffer for extracting data as well as a TcpClient
NetworkStream stream = client.tcpClient.GetStream();
stream.BeginRead(client.buffer, 0, client.tcpClient.ReceiveBufferSize, new AsyncCallback(StreamReadCompleteCallback), client);
}
catch (Exception ex) {
onStatusUpdate(ex.Message);
}
}
在我的回调函数StreamReadCompleteCallback 中,我调用了EndRead,通过检查EndRead 的返回值来检测连接是否已经关闭。如果返回值大于零,我提取/处理读取的数据并在同一客户端上再次调用 BeginRead。如果返回值为零,则连接已关闭,我将删除连接(从列表中删除,关闭 TcpClient 等)。
private void StreamReadCompleteCallback(IAsyncResult ar) {
ConnectedClient client = (ConnectedClient)ar.AsyncState;
try {
NetworkStream stream = client.tcpClient.GetStream();
int read = stream.EndRead(ar);
if (read != 0) {
// data extraction/light processing of received data
client.Append(read);
stream.BeginRead(client.buffer, 0, client.tcpClient.ReceiveBufferSize, new AsyncCallback(StreamReadCompleteCallback), client);
}
else {
DisconnectClient(client);
}
}
catch (Exception ex) {
onStatusUpdate(ex.Message);
}
}
所有这些工作正常,我可以接受连接并从多个客户端设备读取等。
我的问题是:这种从连接的客户端持续读取的方法导致每个连接都有一个等待 BeginRead 返回的工作线程。
因此,如果我有 10 个连接,我将进行 10 个 BeginReads。
让这么多工作线程等待读取似乎很浪费。还有其他更好的方法来完成这个吗?如果我有大量事件连接,我最终会用完内存来添加连接。
有一个线程轮询每个连接的 DataAvailable 属性直到出现某些东西,然后让一个线程读取/处理是一个解决方案吗?
或者创建所有这些工作线程并不像我想的那么重要?
最佳答案
This method of continuously reading from connected clients causes each connection to have a worker thread that is waiting for BeginRead to return
不,它没有。事实上,使用 BeginRead()
或在 Socket
上处理 I/O 的其他异步替代方法之一object 是最具可扩展性的使用方法。
Would having a thread that polls the DataAvailable property of each connection until something shows up, and then makes a thread to read/process be a solution?
没有。这太可怕了。通过 DataAvailable
轮询套接字或 Select()
, 效率非常低,迫使大量的 CPU 时间投入到检查套接字状态上。操作系统提供了很好的异步机制来处理这个问题;轮询实现会忽略这一点并自行完成所有工作。
Or is creating all these worker threads not as big of a deal as I think?
您并不是在创建您认为的线程。当您使用异步 API 时,它们会利用窗口中称为 I/O 完成端口 的功能。 I/O Completion Port 与 I/O 操作相关联,线程可以在端口上等待。但是一个线程可以处理大量操作的等待,因此有 10 个未完成的读取操作实际上不会导致创建 10 个不同的线程。
.NET 管理一个线程池来处理这些操作,作为 ThreadPool
的一部分进行管理类(class)。您可以监视该类以查看 IOCP 池的行为(这与用于 QueueUserWorkItem()
的工作线程池不同)。
.NET 将根据需要分配新的 IOCP 对象和线程来为您的网络 I/O 操作提供服务。您可以放心,它将以合理、高效的方式进行。
在非常大的规模下,与读取操作相关的对象的垃圾收集开销可能会发挥作用。在这种情况下,您可以使用 ReceiveAsync()
方法,它允许您为操作重用自己的状态对象池,这样您就不会不断地创建和丢弃对象。
另一个可能出现的问题是内存碎片,尤其是在大对象堆中(取决于您使用的缓冲区的大小)。当您在套接字上开始读取操作时,必须固定缓冲区,以防止 .NET 压缩它所在的堆。
但这些问题并不是避免使用异步 API 的理由(事实上,第二个问题无论如何都会发生)。它们只是需要注意的事情。使用异步 API 实际上是最好的方法。
也就是说,BeginReceive()
是“守旧派”。它有效,但你可以包装一个 BeginReceive()
在 Task
中运行(参见 Task.FromAsync()
和 TPL 和 Traditional .NET Framework Asynchronous Programming ),或者您可以包装整个 Socket
在NetworkStream
对象(具有 ReadAsync()
和类似的方法),这将允许您以不需要使用显式回调方法的更具可读性的方式编写异步代码。对于网络 I/O 总是以与 UI 的某些交互结束的场景,允许您使用 async
/await
再次以更易读、更易于编写的方式这样做。
关于c# - 连续读取 CF 上的多个 TCP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44439604/
#include using namespace std; class C{ private: int value; public: C(){ value = 0;
这个问题已经有答案了: What is the difference between char a[] = ?string?; and char *p = ?string?;? (8 个回答) 已关闭
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 7 年前。 此帖子已于 8 个月
除了调试之外,是否有任何针对 c、c++ 或 c# 的测试工具,其工作原理类似于将独立函数复制粘贴到某个文本框,然后在其他文本框中输入参数? 最佳答案 也许您会考虑单元测试。我推荐你谷歌测试和谷歌模拟
我想在第二台显示器中移动一个窗口 (HWND)。问题是我尝试了很多方法,例如将分辨率加倍或输入负值,但它永远无法将窗口放在我的第二台显示器上。 关于如何在 C/C++/c# 中执行此操作的任何线索 最
我正在寻找 C/C++/C## 中不同类型 DES 的现有实现。我的运行平台是Windows XP/Vista/7。 我正在尝试编写一个 C# 程序,它将使用 DES 算法进行加密和解密。我需要一些实
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
有没有办法强制将另一个 窗口置于顶部? 不是应用程序的窗口,而是另一个已经在系统上运行的窗口。 (Windows, C/C++/C#) 最佳答案 SetWindowPos(that_window_ha
假设您可以在 C/C++ 或 Csharp 之间做出选择,并且您打算在 Windows 和 Linux 服务器上运行同一服务器的多个实例,那么构建套接字服务器应用程序的最明智选择是什么? 最佳答案 如
你们能告诉我它们之间的区别吗? 顺便问一下,有什么叫C++库或C库的吗? 最佳答案 C++ 标准库 和 C 标准库 是 C++ 和 C 标准定义的库,提供给 C++ 和 C 程序使用。那是那些词的共同
下面的测试代码,我将输出信息放在注释中。我使用的是 gcc 4.8.5 和 Centos 7.2。 #include #include class C { public:
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我的客户将使用名为 annoucement 的结构/类与客户通信。我想我会用 C++ 编写服务器。会有很多不同的类继承annoucement。我的问题是通过网络将这些类发送给客户端 我想也许我应该使用
我在 C# 中有以下函数: public Matrix ConcatDescriptors(IList> descriptors) { int cols = descriptors[0].Co
我有一个项目要编写一个函数来对某些数据执行某些操作。我可以用 C/C++ 编写代码,但我不想与雇主共享该函数的代码。相反,我只想让他有权在他自己的代码中调用该函数。是否可以?我想到了这两种方法 - 在
我使用的是编写糟糕的第 3 方 (C/C++) Api。我从托管代码(C++/CLI)中使用它。有时会出现“访问冲突错误”。这使整个应用程序崩溃。我知道我无法处理这些错误[如果指针访问非法内存位置等,
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 7 年前。
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,因为
我有一些 C 代码,将使用 P/Invoke 从 C# 调用。我正在尝试为这个 C 函数定义一个 C# 等效项。 SomeData* DoSomething(); struct SomeData {
这个问题已经有答案了: Why are these constructs using pre and post-increment undefined behavior? (14 个回答) 已关闭 6
我是一名优秀的程序员,十分优秀!