简体   繁体   中英

.NET TCP socket with session

Is there any way of dealing with sessions with sockets in C#?

Example of my problem:
I have a server with a socket listening on port 5672.

TcpListener socket = new TcpListener(localAddr, 5672);  
socket.Start();  
Console.Write("Waiting for a connection... ");  

// Perform a blocking call to accept requests.  
TcpClient client = socket.AcceptTcpClient();  
Console.WriteLine("Connected to client!");

And i have two clients that will send one byte. Client A send 0x1 and client B send 0x2. From the server side, i read this data like this:

Byte[] bytes = new Byte[256];
String data = null;

NetworkStream stream = client.GetStream();
while ((stream.Read(bytes, 0, bytes.Length)) != 0)
{
     byte[] answer = new ...
     stream.Write(answer , 0, answer.Length);
}  

Then client A sends 0x11. I need a way to know that this client is the same that sent "0x1" before.

Each TcpClient instance is for a different connection. A connection in TCP consists of four things: source IP, source port, target IP, target port. So, even if you have the same target IP and port, and the same source port, you have two different connections.

Data sent by one client will not be mixed in with data sent by the other client. Data sent by a client on a connection will be received in order over that connection.

The only time that Sessions become an issue is to remember the client after the connection is closed.

There is a lot of existing literature on how sessions are implemented in the Web world (HTTP).

One key is whether you are closing the client connections, or are they persistent? If they are persistent, then simply identify them by their object reference. If not, then...

1) You can do simple sessions based on the source IP address. But if multiple clients are behind a NAT firewall, sharing the IP, then that doesn't work, see the next option.

2) Use a "cookie"

3) Use authentication to identify each client

Every option except IP based sessions requires adding something to the protocol itself.

Some things to remember with sockets. The remote IP + remote port uniquely identifies a client TCP socket. Multiple connections from the same remote client will have diffent remote ports. But you cannot rely on that if the socket closes, because the remote OS may recycle the remote port for a new connection once the old one times out.

You would probably need to implement your own protocol in order to identify the clients. Perhaps define a chunk of bytes, where in addition to the data you also include a client identifier.

您将需要某种身份验证或预先协商的令牌,并且所有这些都用某种盐加密。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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