0

So I am trying to setup a client websocket in a Javascript file talking to a server written in C#.

Client:

var socket = new WebSocket("ws://localhost:11000");

function barf() {
    socket.send('asdf');
}

socket.onmessage = function(e){
     console.log(e.data);
     };

Server:

IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[1];
TcpListener listener = new TcpListener(ipAddress, 11000);

try
{

    listener.Start();
    TcpClient client = listener.AcceptTcpClient();

    message = client.GetStream();
    int i = message.Read(bytes);

    string data = Encoding.ASCII.GetString(bytes, 0, i);

    string key = new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim();

    Byte[] response = GetHandshakeResponse(key);
    message.Write(response, 0, response.Length);

    bytes = new Byte[1024];
    i = message.Read(bytes);

    Console.WriteLine(Encoding.ASCII.GetString(bytes));
}

The issue is that when I call the function 'barf' in my Javascript file, the server spits out a different message each time as if it were being encrypted. I have tried using different encodings and I can't seem to end up with exactly 'asdf' on the server. Does anyone have any insight? Thanks!

  • Did you try UTF-8 instead of ASCII? – Guerric P Sep 22 '20 at 15:58
  • I did try to use UTF-8. The response still comes out as gibberish. – ChapterSevenSeeds Sep 22 '20 at 15:59
  • There is more to Web socket communication than just linking it up to raw sockets and reading from them – ControlAltDel Sep 22 '20 at 16:01
  • The gibberish is because you are sending a TCP message, the WebSocket connection is not established at this point. You should read some tutorial about how to implement a WebSocket server in C# with the HTTP switching protocols – Guerric P Sep 22 '20 at 16:01
  • [`WebSocket.send(string)` sends `USVString` data as UTF-8.](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send) – Heretic Monkey Sep 22 '20 at 16:02
  • https://stackoverflow.com/questions/10200910/creating-a-hello-world-websocket-example – ControlAltDel Sep 22 '20 at 16:07
  • MDN has a [really simple sample](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_server) of a websocket server in c# – stuartd Sep 22 '20 at 16:08
  • So the MDN article was exactly what I needed. I went through so many articles about Websockets and apparently none of them explained how the bytes are encoded with a mask. After that implementation, I got it to work. Thanks you guys! – ChapterSevenSeeds Sep 22 '20 at 20:50

1 Answers1

0

If you want to encrypt communication over web sockets, use the wss protocol instead of ws.

Also, I don't think your test is meaningful, because you haven't run it with a server socket server on the back end.

Creating a "Hello World" WebSocket example

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80