-1

我需要在服务器和客户端之间建立双向(全双工)链接(我可以同时发送和接收数据)。通过我所做的研究,我发现最好的方法是让两个线程分别在客户端和服务器之间实现一个套接字。有没有人知道如何解决这个问题,或者看过一些类似的代码?我对这个领域真的很陌生,真的很欢迎任何建议......

4

1 回答 1

1

You don't need two sockets for full duplex communication, unless you are using a higher level transport protocol that is limiting your ability to do simultaneous sends and receives.

One example of such a transport limitation would be if your server is really an HTTP server. Then, if you need bi-directional communication with your application using HTTP, you may need one connection that is performing a GET, and another connection that is performing a PUT.

Otherwise, your client is able to read and write to the same socket simultaneously. You can create 2 threads, where one is reading, and the other is writing, but they would each be operating on the same socket.

Your server could use a similar strategy (a pair of threads per connection), but if the server is handling many connection (say thousands), then you may face scalability issues. Typically, this is solved using non-blocking I/O with some high performance connection multiplexer, like epoll() or kqueue(), and you only create as many threads as you have cores to distribute the connection processing load. Check out The C10K Problem for a good source of information on how to implement highly scalable servers.

于 2013-07-12T22:00:21.950 回答