BhushanK
BhushanK

Reputation: 1243

Differentiate between TcpClient and WebSocket?

I am developing an application in which i am using socket for the communication between server application and client application(web and desktop both).
My server application continuously listening the request of the client application and accept the request whenever comes.
Server code :

TcpListener listener = new TcpListener(IPAddress.Parse(ipAddStr), portNum);
listener.Start();
while (listen)
{
    TcpClient handler = listener.AcceptTcpClient();
    // doing some stuff
    // for every client handler i am creating a new thread and start listening for the next request
}

and for web client i am using WebSocket, as for establishing the connection with WebSocket client we have to follow some handshaking process. and for that I am using the following code (which is working fine) :

    static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    private static string AcceptKey(ref string key)
    {
        string longKey = key + guid;
        SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey));
        return Convert.ToBase64String(hashBytes);
    }

generating and sending response for handshaking with websocket client:

       // generate accept key fromm client header request
        var key = headerRequest.Replace("ey:", "`")
                         .Split('`')[1]                     
                         .Replace("\r", "").Split('\n')[0]  
                         .Trim();
        var responseKey = AcceptKey(ref key);

        //create the response for the webclient
        var newLine = "\r\n";
        var response = "HTTP/1.1 101 Switching Protocols" + newLine
                     + "Upgrade: websocket" + newLine
                     + "Connection: Upgrade" + newLine
                     + "Sec-WebSocket-Accept: " + responseKey + newLine + newLine;

        //send respose to the webclient
        Byte[] sendBytes = Encoding.ASCII.GetBytes(response);
        networkStream.Write(sendBytes, 0, sendBytes.Length);
        networkStream.Flush();

I have also TcpClient socket used for desktop application, so the problem is how to identify that the request is from WebSocket or from TcpClient ?

Upvotes: 2

Views: 4392

Answers (2)

Philipp
Philipp

Reputation: 69703

The easiest way would be to have a websocket listener and the vanilla TCP listener listen to different port numbers. You should do that anyway, because it is customary for websocket applications to run on the standard http port 80 (or standard https port 443 when you use websockets with TLS), while a custom protocol based on TCP should run on one of the ports from the "registered" range between 1024 to 49151. You are well-advised to follow this, because a well-secured client environment which allows web access but not much else might not allow the user to connect to other ports than 80 and 443, while any non-http traffic on these ports might trigger an intrusion detection system.

When you still want to handle both protocols on the same port for some reason, it will be a bit difficult. Websocket is a protocol based on TCP which looks like a vanilla HTTP GET request at first, until you receive the headers Connection: Upgrade and Upgrade: websocket.

That means connection requests for either protocol need to be accepted by the same listener at first. Only after the client sent enough data to identify its connection attempt as either your custom protocol or websocket (or something completely different which accidentally connected to your port - you will encounter that a lot when you deploy your application facing the internet) and then delegate the communication with the client to the appropriate handler class.

Upvotes: 1

vtortola
vtortola

Reputation: 35945

A TcpClient is a Socket wrapper.

WebSocket is a protocol that can run over a TcpClient. WebSocket protocol defines the handshake and how to frame data.

The best way of differentiate simple TCP connections and WebSocket connections is to have them listening in different ports, since you are going to use different protocols. It would be bad if you have them in the same port, it will become a mess.

Upvotes: 1

Related Questions