Creating a "Hello World" WebSocket example
Asked 07 September, 2021
Viewed 2.3K times
  • 61
Votes

I don't understand why I cannot make the following code work. I want to connect with JavaScript to my server console application. And then send data to the server.

Here is the server code:

    static void Main(string[] args)
    {            
        TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 9998);
        server.Start();
        var client = server.AcceptTcpClient();
        var stream = client.GetStream();

        while (true)
        {
            var buffer = new byte[1024]; 
            // wait for data to be received
            var bytesRead = stream.Read(buffer, 0, buffer.Length);                
            var r = System.Text.Encoding.UTF8.GetString(buffer);
            // write received data to the console
            Console.WriteLine(r.Substring(0, bytesRead));
        }
    }

and here is the JavaScript:

        var ws = new WebSocket("ws://localhost:9998/service");
        ws.onopen = function () {
            ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
        };

        ws.onmessage = function (evt) {
            var received_msg = evt.data;
            alert("Message is received...");
        };
        ws.onclose = function () {
            // websocket is closed.
            alert("Connection is closed...");
        };

When I run that code this is what happens:

Note that when I run the JavaScript the server accepts and successfully establishes a connection. JavaScript is not able to send data though. Whenever I place the send method it will not send even though a connection is established. How can I make this work?

5 Answer