Bercovici Adrian
Bercovici Adrian

Reputation: 9380

Can not accept socket connections on server

I have created a .NET Console App in which i want to accept client websockets.(I am using the chrome extension -Simple Web Socket Client). When i try to send messages to the connected clients i get this error in the browser :

    WebSocket connection to 'ws://localhost:8600/' failed: 
    Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE
    CLOSED: ws://localhost:8600

Server

class Program
    {
        static async Task Main(string[] args)
        {
            CancellationTokenSource src = new CancellationTokenSource();

            Console.WriteLine("starting server...");
            Task server = Task.Run(async () =>
            {
                Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                var point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8600);

                serverSocket.Bind(point);
                Console.WriteLine("Listening on localhost:8600" );
                serverSocket.Listen(6);
                var client = await serverSocket.AcceptAsync();
                Task clientTask = Task.Run(async () =>
                {
                    while (true)
                    {
                        await client.SendAsync(Encoding.UTF8.GetBytes("Date is" + DateTime.Now.ToString()), SocketFlags.None);
                        await Task.Delay(5000);
                    }
                },src.Token);

            }, src.Token);
            while (true)
            {
                if (Console.ReadKey().Key == ConsoleKey.A)
                {
                    src.Cancel();
                    break;
                }
            }
        }
    }

From Simple Web Socket Client ( chrome extension) i try to connect to : ws://localhost:8600

P.S I am not sure about passing the same token in all tasks , but besides this i do not know why it keeps with this error.

Upvotes: 0

Views: 890

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 598309

Your server code is not implementing the HTTP or WebSocket protocols at all.

A WebSocket session begins life as an HTTP session, where the client sends an HTTP request asking the server to upgrade the connection to the WebSocket protocol, and the server's HTTP response then indicates whether that upgrade was successful or not, before any WebSocket messages can then be exchanged.

Your server is just opening a plain ordinary TCP port and then sending arbitrary string data as soon as the client connects. You are not following the HTTP or WebSocket protocols at all. So, of course, a WebSocket client will report a failure to establish a WebSocket session. Your server is not sending back a valid HTTP upgrade response (just as the client error says).

Instead of using the Socket class directly, try using the HttpListener and HttpListenerWebSocketContext classes instead. For example:

How to work with System.Net.WebSockets without ASP.NET?

Upvotes: 2

Related Questions