简体   繁体   English

TCP推挽套接字服务器设计

[英]TCP push-pull socket server design

I am designing a cross-platform messaging service as a learning exercise. 我正在设计一个跨平台的消息服务作为一项学习练习。 I have programmed socket-based servers before, but always a "client-polls-server" design, like a web server. 我以前曾经对基于套接字的服务器进行过编程,但始终像Web服务器一样采用“客户端轮询服务器”设计。 I want to be able to target mobile platforms, and I read that polling is a battery drain, so I would like to do push notification. 我希望能够定位到移动平台,并且我读到轮询会消耗大量电池,因此我想进行推送通知。

The server will be TCP-based, written in C++. 该服务器将基于C ++,基于TCP。 What I'm having trouble getting my head around is how to manage the bi-directional nature of the design. 我遇到麻烦的是如何管理设计的双向性。 I need a client to be able to send packets to the server as normal, but also listen for packets. 我需要一个客户端能够像往常一样将数据包发送到服务器,而且还要侦听数据包。 How do I mitigate situations like, the client is sending data when the server is trying to send to it, or it's blocked listening for data but then needs to send something? 我该如何缓解这种情况,例如,当服务器尝试向客户端发送数据时客户端正在发送数据,或者它阻止了侦听数据,但随后又需要发送数据?

For example, consider the following crude diagram: 例如,考虑以下粗图:

原始图

So, let's say client A is in the middle of sending a chunk of data (arrow 1). 因此,假设客户端A正在发送大量数据(箭头1)。 While this is happening, client B sends a message (arrow 2), which causes the server to attempt to send data back to client A (arrow 3), but client A hasn't finished sending arrow 1 yet. 发生这种情况时,客户端B发送一条消息(箭头2),这导致服务器尝试将数据发送回客户端A(箭头3),但是客户端A尚未完成箭头1的发送。 What happens in this instance? 在这种情况下会发生什么? Should I setup 2 separate ports on each client, one for inbound, one for outbound? 是否应该在每个客户端上设置2个单独的端口,一个用于入站,一个用于出站? Do I need to keep track of the state of each connection? 我需要跟踪每个连接的状态吗?

Or is there a better approach to this altogether? 还是有更好的方法来解决这个问题?

One socket port is inherently bidirectional. 一个套接字端口本质上是双向的。 To handle both inbound and outbound traffic more or less concurrently you need to use nonblocking sockets. 要或多或少同时处理入站和出站流量,您需要使用非阻塞套接字。

I think the solution is pretty simple. 我认为解决方案非常简单。 The TCP server should have a list with connected clients. TCP服务器应具有连接的客户端的列表。 Since a TCP connection is bi-directional, the push mechanism is quite simple. 由于TCP连接是双向的,因此推送机制非常简单。

Another important thing, as long as your server isn't multithreaded, you can read from or write to one client at the same time. 另一重要的事情是,只要您的服务器不是多线程的,您就可以同时读取或写入一个客户端。

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

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