java 单线程之tcp,如何通过单线程在TCP上实现全双工通道?

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 mostly 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值