4

I'm trying to create a simple C# websocket server with websocket-sharp and I followed the official guide but I got some peculiar reply instead.

C# Snippet

using System;
using WebSocketSharp.Server;

namespace WebSocketSharp
{
class MainClass
{
    public static void Main(string[] args)
    {
        startServer();
    }

    public static void startServer()
    {
        var ws = new WebSocketServer(System.Net.IPAddress.Any, 8181);
        ws.Start();
        Console.WriteLine("Server started");
        Console.ReadKey(true);
        ws.Stop();
        Console.WriteLine("Server stopped");
    }
}
}

When I tried to connect my client (HTML) to the server, I got a message

WebSocket connection to 'ws://127.0.0.1:8181/' failed: Error during WebSocket handshake: Unexpected response code: 501

and this showed up at my terminal at the same time image

According to HTTP Protocol, code 501 means

The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.

This is my client code and I believe it conforms with the request method.

<!doctype html>
<head>

</head>
<body>
  <form>
    <input id="textField1" type="text" style="margin: 0 5px; width: 200px; height: 40px;" placeholder="Enter data">
    <button id="sendTextField1" type="button" class="btn btn-info">Send</button>
  </form>
  <script type="text/javascript">
    var start = function () {
    var wsImpl = window.WebSocket || window.MozWebSocket;
    window.ws = new wsImpl('ws://127.0.0.1:8181/');

    ws.onmessage = function (evt) {
      console.log(evt.data);
    };
    ws.onopen = function () {
      console.log("Connected");
    };
    ws.onclose = function () {
      console.log("Closed");
    };

    document.getElementById("sendTextField1").onclick = function() {
      sendToSocket(document.getElementById('textField1').value);
    };

    function sendToSocket(value){
      console.log("Sending value to socket " + value + " ");
      ws.send(value);
    };
}
window.onload = start;

Can anyone tell me where is my mistake?

J.Doe
  • 1,097
  • 1
  • 16
  • 34

3 Answers3

4

I think the problem is you're not adding a behavior to the server. I did the "laputa" thing that is mentioned in the docs here: https://github.com/sta/websocket-sharp.

Don't forget to connect to the right endpoint. In the example the endpoint is "/laputa", so you have to connect in your javascript like:

var socket = new WebSocket('ws://127.0.0.1:8081/laputa');
Jaap Weijland
  • 3,146
  • 5
  • 23
  • 31
  • I have same problem, but i made a class ServerSocket : WebSocketBehavior, and made a overrided methods OnOpen OnError OnClose and OnMessage. is it mandatory to make it like in sample from gh you sent? i mean, have i type events like ```ws.OnClose += (sender, e) => { ... };``` ? – Kamil Apr 29 '19 at 17:14
1

You need to add a class inherited from WebSocketBehavior, I`m not sure the library will work without it.

The example did not work for me though, I had to call server.Start() before adding behaviors.

Atchitutchuk
  • 174
  • 5
0

I thought this would be helpful as the core of the question is on how to setup the WebSocket server and having some basic exchange with a client. This minimal code creates both, a local Server & Client, who perform a primitive exchange in purpose of demonstrating the basic communication between them:

using System;
using WebSocketSharp;
using WebSocketSharp.Server;

namespace ConsoleApp1
{
    public class ConsoleApplication
    {
        public class ServerService : WebSocketBehavior
        {
            protected override void OnMessage(MessageEventArgs e)
            {
                Console.WriteLine("I, the server, received: " + e.Data);

                Send("I, the server, send you this!");
            }
        }

        public static void Main(string[] args)
        {
            // Server

            var wssv = new WebSocketServer(1236);
            wssv.AddWebSocketService<ServerService>("/service");
            wssv.Start();

            Console.WriteLine("Server is setup.");
            Console.ReadLine();

            // Client

            var ws = new WebSocket("ws://127.0.0.1:1236/service");

            ws.OnMessage += (sender, e) => Console.WriteLine("I, the client, received: " + e.Data);

            ws.Connect();

            Console.WriteLine("Client is setup.");
            Console.ReadLine();

            // The client sends a message to the server:

            ws.Send("Server, please send me something!");

            Console.ReadLine();
        }

    }
}