开发者

When to use different ports for client-server application?

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 开发者_C百科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.


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:

  1. Connection where requests flow from client to server
  2. Connection where requests flow from server to client

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜