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 7169845
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T15:05:36+00:00 2026-05-28T15:05:36+00:00

Below i have shared my code in detail. I read documentation and everything about

  • 0

Below i have shared my code in detail. I read documentation and everything about handshake. I followed all the steps given in documentation and numerous examples on the internet but still i have this problem. Strange thing id websocket.onclsose() got triggered when I close the server.


// Simple Websocket server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Security.Cryptography;

using System.Threading;

namespace WebSocketServer
{
class Program
{
    //port 
    private static int _port = 8181;

    static void Main(string[] args)
    {
        TcpListener t = new TcpListener(IPAddress.Loopback, _port);
        t.Start();

        Console.WriteLine("Server is started and waiting for client\n\n");

        byte[] buff = new byte[255];
        NetworkStream stream;
        TcpClient client;
        while(true)
        {
            client = t.AcceptTcpClient();
            if (!client.Connected)
               return;

            // I need form a proper mechanism to get all the data out of network stream.
            // If I wait too long client get disconnected and we dont get stream and if
            // if we dont wait at all then data doesnt reach server port and hence cant
            // read the handshake.

            stream = client.GetStream();
            while ((stream.Read(buff, 0, buff.Length)) != 0)
            {
                break;
            }

            if (0 != buff.Length)
                break;
        }

        StreamWriter writer = new StreamWriter(stream);                  
        writer.AutoFlush = true;


        //while (stream.DataAvailable)
            //stream.Read(buff, 0, buff.Length);

        Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(buff));
        string clientHandshake = System.Text.ASCIIEncoding.ASCII.GetString(buff);

        char[] separators = new char[1];
        separators[0] = '\n';
        string[] temp = clientHandshake.Split(separators, 100);
        string keyword = "Sec-WebSocket-Key";
        string key = "";
        foreach (string s in temp)
        {
            if (s.Contains(keyword))
            {
                string keyTemp= s.Substring(keyword.Length + 2);
                key = keyTemp.Remove(keyTemp.Length - 1);


                break;
            }
        }

        string responseKey = GetServerResponseKey(key);

        // Send Server handshake
        string handshake =
            "HTTP/1.1 101 Switching Protocols\r\n" +
            "Upgrade: websocket\r\n" +
            "Connection: Upgrade\r\n" +
            "Sec-WebSocket-Accept: " + responseKey + "\r\n";

        writer.Write(handshake);
        writer.Flush();

        Console.WriteLine(handshake);

        while ((stream.Read(buff, 0, buff.Length)) != 0)
        {
            break;
        }

        Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(buff));


        // Keep Server alive
        while (true)
        { }
    }

    //Helper method to convert string into Byte[]
    private static byte[] GetByteArray(string str)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        return encoding.GetBytes(str);
    }

    //This method is requuired because it combines key(got it from client)
    //with GUID. Then takes SHA1 hash of that string and then encode to base64.
    //This is all required because Handshake mechanism can be done by only this 
    //way according to Websocket Protocol(http://datatracker.ietf.org/doc/rfc6455/) 
    private static string GetServerResponseKey(string key)
    {
        Console.WriteLine("original key = " + key);

        string keyForHash = String.Concat(key, Guid.NewGuid());
        Console.WriteLine("text version of server response key = " + keyForHash);

        UTF8Encoding encoding = new UTF8Encoding();
        byte[] temp = encoding.GetBytes(keyForHash);

        SHA1 hashProvider = new SHA1CryptoServiceProvider();
        byte[] keyForBase64 = hashProvider.ComputeHash(temp);

        return Convert.ToBase64String(keyForBase64);

    }
}
}

// Simple WebSocket Client

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebSocketClient._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>

<script language="javascript" type = "text/javascript">
    var ws;
    function btnConnectSend_onclick() {
        if ("WebSocket" in window) {
            ws = new WebSocket("ws://localhost:8181");
            ws.onopen = function() {
                alert("Connection Open");
                ws.send("Hello Server");
            };
            ws.onmessage = function(evt) {
                form1.txtMessage.value = evt.data;
                alert("Server says:" + evt.data);
            };
            ws.onclose = function() {
                alert("Socket Closed!!!");
            };

            ws.onerror = function() {
                alert("WTF!");
            };
        }
    }

    function btnClose_onclick() {
        ws.close();
    };
</script>
</head>

<body>
<form id="form1" runat="server">
<div style="height: 350px">
    <input id="btnConnectSend" type="button" value="Connect/Send" onclick ="return btnConnectSend_onclick ()"/>
    <br />
    <input id="txtMessage" type="text"/>
    <br />
    <input id="btnClose" type="button" value="Close" onclick="return btnClose_onclick()"/>
</div>
</form>
</body>
</html>
  • 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-05-28T15:05:37+00:00Added an answer on May 28, 2026 at 3:05 pm

    I think you have a bug in GetServerResponseKey(). keyForHash should be assigned to String.Concat(key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")

    The value you append to the client’s key must hard-coded and cannot be a dynamically generated guid. See pt 5 in section 4.2.2 of the spec.

    Another point, you should consider checking the request for a Sec-WebSocket-Protocol header. If this is sent by the client, it’ll expect you to echo the header in your handshake response (always assuming your server supports the sub-protocol of course). This won’t cause a handshake to stall but may later cause the client to reject your handshake response.

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

Sidebar

Related Questions

I have the following code which throws an exception (detail in code comments below).
Below I have written a sample program that I have written to learn about
below i have a code that runs in most of my simple programs ..
I have below html code in my aspx. <input type=hidden id=medicalLink value='<a href=/forms/contactus.aspx >Contact
I have below code in html. <li class=selected runat=server id=lihome><a href=/ISS/home.aspx title=Home><span>Home</span></a></li> Now I
I have below is the html code for TD which gets appended after matching
Below is the plugin code that i have tried to reuse from an old
I have integrated the below code in my application to generate a 'pdf' file
I have a situation where T4MVC is generating everything properly (meaning intellisense shows all
I have a Class Library project which houses some shared code between other projects

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.