0

I created a system to connect a series of TcpClient to a TcpListener and exchange data in a chat-like system. Once the connection is established, the server adds the client to a List, and starts reading the stream waiting for messages.

Once the server has received a message, is there a build-in method to know which client sent it?

Alternative: I thought of attaching the client's RemoteEndPoint (Ip + port) to the message to use it as an identifier, which should be the same between the two versions of the TcpClient on the client and on the server, and unique compared to the other clients. Am I right?

Presi
  • 806
  • 10
  • 26
  • The state, I would think. – ProgrammingLlama Mar 31 '20 at 07:44
  • If the client loses and reestablishes connection, it may have another port but still be the same client... (logical client, not the same instance of TcpClient) – Fildor Mar 31 '20 at 07:56
  • I don't mind, if the client loses and reestablishes connection they will get a new identity, no problem for that. @John mmm, i don't know what's that, can you explain ^^? – Enrico Calzolai Mar 31 '20 at 08:04

1 Answers1

1

Once the server has received a message, is there a build-in method to know which client sent it?

Anything there is for you to add; typically you would maintain some nominal per-connection state alongside each Socket / TcpClient / TcpListener / NetworkStream / Pipe (your choice of API) instance, so that when receiving a message you can trivially look up whatever you need. In some cases, it may be succifient to just use the Socket / TcpClient / etc instance as a key, but more often you'll have some kind of user-state/context information. This is basically entire up to you to implement.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Ok thankyou! But, for exemple, is the RemoteEndPoint a unique data that identifiy the TcpClient, right? – Enrico Calzolai Mar 31 '20 at 09:07
  • @EnricoCalzolai well, *sort of*, but no more than the socket/tcpclient/etc would - and it isn't as useful as a custom state object – Marc Gravell Mar 31 '20 at 09:12
  • In fact, I thought to get the RemoteEndPoint from the Client/Socket properties of the TcpClient. What other unique properties that I can transfer via stream are you referring to? – Enrico Calzolai Mar 31 '20 at 10:26
  • 1
    @EnricoCalzolai whatever app-specific context your code needs; for example, many APIs have some kind of auth/handshake, so you might be tracking a user token, a protocol sub-version, and any other connection state you need, "current room", for example, in the context of a chat application – Marc Gravell Mar 31 '20 at 11:03