开发者

How to implement a full duplex channel over TCP with a single thread?

开发者 https://www.devze.com 2023-02-03 18:49 出处:网络
The network lib I\'m writing needs to send and receive messages through a TCP socket. Messages can be sent or received any time, i.e should work as a full duplex channel.

The network lib I'm writing needs to send and receive messages through a TCP socket. Messages can be sent or received any time, i.e should work as a full duplex channel.

I was able to implement such scenario using two threads: main thread calling send() and a dedicated thread mo开发者_如何学Gostly blocked at recv() call.

My question is: is it possible to implement the same scenario with a single thread? I.e. by registering some callback function?

As a side note: I need implement this scenario in C++, Java and Python.


Yes, it possible. You need to use an API that allows multiplexed I/O. Under C/C++ and Python you can use select() and non-blocking I/O, so that the only networking call you ever block in is select(). There is also poll() and epoll() and a number of other similar APIs that accomplish the same thing, with varying degrees of efficiency and portability. Java has non-blocking I/O APIs also.

Another possibility is to use asynchronous I/O, where you tell the OS to start an I/O transaction and it notifies you (by some mechanism) when it has finished the operation. I'm not familiar with that style of network programming, however, so I won't try to give details.


In general, a library would do this by providing an interface into the application's main loop / event loop.

For example, most single-threaded network-using applications would have a main loop that blocks in select(), poll() or similar. Your library would just return a file descriptor that the application should include in its select() / poll() call, and a callback function that the application should call when that file descriptor is readable.

0

精彩评论

暂无评论...
验证码 换一张
取 消