开发者

.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 ...
     str开发者_运维问答eam.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.


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.


You'll need some sort of authentication or pre-negotiated token, and all of this somehow encrypted with some salt.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜