Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9219141
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T03:02:13+00:00 2026-06-18T03:02:13+00:00

I’m a beginner with the WebSocket API. I’m trying to connect to my server

  • 0

I’m a beginner with the WebSocket API. I’m trying to connect to my server locally but I’m obtaining the connection closed message. Can anyone tell me what I am doing wrong?

That’s my code:

Server

using System.Net.Sockets;
using System.Net;
using System.IO;
using System;
class Program
{
    static void Main(string[] args)
    {
        var listener = new TcpListener(IPAddress.Loopback, 8181);
    listener.Start();
    while (true)
    {
        Console.WriteLine("Listening...");
        using (var client = listener.AcceptTcpClient())
        using (var stream = client.GetStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        {

            string line = null, key = "", responseKey = "";
            string MAGIC_STRING = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
            while (line != "")
            {
                line = reader.ReadLine();
                if (line.StartsWith("Sec-WebSocket-Key:"))
                {
                    key = line.Split(':')[1].Trim();
                }
            }

            if (key != "")
            {
                key += MAGIC_STRING;
                using (var sha1 = SHA1.Create())
                {
                    responseKey = Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(key)));
                }
            }

            // send handshake to the client
            writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
            writer.WriteLine("Upgrade: WebSocket");
            writer.WriteLine("Connection: Upgrade");
            writer.WriteLine("WebSocket-Origin: http://localhost:8080");
            writer.WriteLine("WebSocket-Location: ws://localhost:8181/websession");
            if (!String.IsNullOrEmpty(responseKey))
                writer.WriteLine("Sec-WebSocket-Accept: " + responseKey);
            writer.WriteLine("");
            Console.ReadLine();
            writer.Flush();

        }//using
        Console.WriteLine("Finished");
    }//while

    }
}

The Client

     <!DOCTYPE HTML>
       <html>
       <head><title></title>
          <script type="text/javascript">

       function WebSocketTest() {
          var msg = document.getElementById("msg");
            if ("WebSocket" in window) {
             msg.innerHTML="WebSocket is supported by your Browser!";
        // Let us open a web socket
        var ws = new WebSocket("ws://localhost:8181/websession");
        ws.onopen = function () {
            // Web Socket is connected, send data using send()
             msg.innerHTML="connection open";
            //ws.send("Message to send");
            //msg.innerHTML="Message is sent...";
        };
        ws.onclose = function () {
            // websocket is closed.
            msg.innerHTML = "Connection is closed...";
        };

        ws.onerror = function(error){
            console.log('Error detected: ' + error);
        };
        ws.onmessage = function (evt) {
            var received_msg = evt.data;
            msg.innerHTML="Message is received...";
        };

    }
    else {
        // The browser doesn't support WebSocket
        msg.innerHTML="WebSocket NOT supported by your Browser!";
    }
   }
   </script>
     </head>
       <body>
       <div id="sse">
        <a href="javascript:WebSocketTest()">Run WebSocket</a><br />
         <p id="msg"></p>
       </div>
        </body> 
           </html>

Any solution would be appreciated and thank you 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T03:02:15+00:00Added an answer on June 18, 2026 at 3:02 am

    That is not a valid web-socket response under any specification. The initial web-socket response always requires you to crunch some numbers as part of the response headers, to prove you’re a web-socket server. Which headers to read and write, and what crunching to do, depends on the version of web-sockets (hibi/hixie 76/rfc). It actually looks like your server is using the headers of a client.

    For example, a RFC6455 (13) response would start:

    HTTP/1.1 101 Switching Protocols
    Upgrade: websocket
    Connection: Upgrade
    Sec-WebSocket-Accept: {crunch some numbers}
    

    Note that a Hixie-76 response is different, and there are bits in the above that I have omitted.

    From the RFC6455 specification:

    To prove that the handshake was received, the server has to take two
    pieces of information and combine them to form a response. The first
    piece of information comes from the |Sec-WebSocket-Key| header field
    in the client handshake:

     Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
    

    For this header field, the server has to take the value (as present in
    the header field, e.g., the base64-encoded [RFC4648] version minus any
    leading and trailing whitespace) and concatenate this with the
    Globally Unique Identifier (GUID, [RFC4122]) "258EAFA5-E914-47DA-
    95CA-C5AB0DC85B11" in string form, which is unlikely to be used by
    network endpoints that do not understand the WebSocket Protocol. A
    SHA-1 hash (160 bits) [FIPS.180-3], base64-encoded (see Section 4 of
    [RFC4648]), of this concatenation is then returned in the server’s
    handshake.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
Does anyone know how can I replace this 2 symbol below from the string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I am trying to understand how to use SyndicationItem to display feed which is
I have a French site that I want to parse, but am running into
I am trying to render a haml file in a javascript response like so:
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
This could be a duplicate question, but I have no idea what search terms
I'm trying to select an H1 element which is the second-child in its group

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.