Come Funziona

Writing a WebSocket server in C# copypaste

Introduction

If you would like to use the WebSocket API, it is useful if you have a server. In this article I will show you how to write one in C#. You can do it in any server-side language, but to keep things simple and more understandable, I chose Microsoft's language.

This server conforms to RFC 6455, so it will only handle connections from Chrome version 16, Firefox 11, IE 10 and over.

First steps

WebSockets communicate over a TCP (Transmission Control Protocol) connection. Luckily, C# has a TcpListener class which does as the name suggests. It is in the System.Net.Sockets namespace.

Note: It is a good idea to include the namespace with the using keyword in order to write less. It allows usage of a namespace's classes without typing the full namespace every time.

TcpListener

Constructor:

TcpListener(System.Net.IPAddress localaddr, int port)

localaddr specifies the IP of the listener, and port specifies the port.

Note: To create an IPAddress object from a string, use the Parse static method of IPAddress.

Methods:

  • Start()
  • System.Net.Sockets.TcpClient AcceptTcpClient() Waits for a Tcp connection, accepts it and returns it as a TcpClient object.

Here's a barebones server implementation:

using System.Net.Sockets;
using System.Net;
using System;

class Server {
    public static void Main() {
        TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);

        server.Start();
        Console.WriteLine("Server has started on 127.0.0.1:80.{0}Waiting for a connection...", Environment.NewLine);

        TcpClient client = server.AcceptTcpClient();

        Console.WriteLine("A client connected.");
    }
}