2

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.

4

1 回答 1

1

很好的问题。我已经用这种架构编写了不止一个应用程序。当您需要进行双向通信时,您需要在客户端和服务器之间建立两个连接(当然,在两个不同的端口):

  1. 请求从客户端流向服务器的连接
  2. 请求从服务器流向客户端的连接

这样,双方都NetworkStream准备好了阅读。您会注意到两个流之间的独立性级别,允许您更好地控制双向请求处理代码。

于 2011-07-25T18:48:17.270 回答