何时为客户端-服务器应用程序使用不同的端口?
我通常什么时候需要不同的端口来进行客户端与服务器的通信? (此问题适用于 C# 和一般套接字编程)。
我已经实现并正在使用一个简单的 C# 客户端-服务器应用程序。基本上:
- 服务器上侦听客户端
- 服务器在接受/连接的
- 生成客户端线程 -
- 服务器等待客户端通话
- 客户端通话
- 服务器响应
- 客户端通话
- 服务器响应等。
如果客户端停止通话,则服务器会在 NetworkStream.Read() 中阻塞code> 模式永远在该生成的线程中,除非客户端断开连接。
我现在正在考虑这样一种情况,双方都保持安静,直到任何一方发生某些事件,然后客户端或服务器才会发送数据。因此,两者都需要以某种方式同时处于 NetworkStream.Read 模式,并且还能够同时相互发送(如果事件同时发生在双方上)。
在这种情况下,我们是否需要不同的端口,或者客户端和服务器都可以处于 NetworkStream.BeginRead 模式,而不会面临 NetworkStream 同时处于写入和发送模式的问题?
谢谢。
When will I normally need different ports for client-server communication?
(This question is for C# and general socket programming).
I have implemented and been using a simple C# client-server application. Basically:
- server listens for client
- on accepted/connected
- server spawn client thread -
- server waits for client to talk
- client talk
- server respond
- client talk
- server respond etc.
if client stops talking, then server blocks in NetworkStream.Read()
mode forever in that spawned thread unless client-side disconnects.
I am now thinking of the situation where both sides keeps quiet until some event happen on either side then only will the client or server sends data across. As such both needs to be in NetworkStream.Read mode concurrently somehow and also be able to send to each other at the same time (if the event happens on both sides simultaneously).
Do we need different ports in this case or can both client and server be in NetworkStream.BeginRead mode without risking a problem with NetworkStream being in both writing and sending mode at the same time?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
很好的问题。我已经用这种架构编写了多个应用程序。当您需要进行双向通信时,客户端和服务器之间需要两个连接(当然,在两个不同的端口):
这样,双方都会准备好读取 NetworkStream。您会注意到两个流程之间的独立程度,使您可以更好地控制双向请求处理代码。
Excellent question. I have written more than one app with that architecture. When you need to have bi-directional communication, you need two connections (of course, in two different ports) between client and server:
That way, both sides will have a
NetworkStream
ready to be read. And you notice the level of independence between the two flows, allowing you more control over your bi-directional request handling code.