Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#作为用于HTML5 Websocket连接的Websocket服务器_C#_Html_Websocket - Fatal编程技术网

C#作为用于HTML5 Websocket连接的Websocket服务器

C#作为用于HTML5 Websocket连接的Websocket服务器,c#,html,websocket,C#,Html,Websocket,我想我该问问别人了。是否可以使用C#和来自HTML5代码的服务器请求创建websocket服务器 我目前正在使用websocket的系统包。我有一个通过互联网下载的代码,它是: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WebSocketChatServer { using WebSocketServer; class Chat

我想我该问问别人了。是否可以使用C#和来自HTML5代码的服务器请求创建websocket服务器

我目前正在使用websocket的系统包。我有一个通过互联网下载的代码,它是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WebSocketChatServer
{
    using WebSocketServer;

    class ChatServer
    {
        WebSocketServer wss;
        List<User> Users = new List<User>();
        string unknownName = "john doe";


        public ChatServer()
        {

            // wss = new WebSocketServer(8181, "http://localhost:8080", "ws://localhost:8181/chat");

            wss = new WebSocketServer(8080, "http://localhost:8080", "ws://localhost:8080/dotnet/Chats");


            wss.Logger = Console.Out;
            wss.LogLevel = ServerLogLevel.Subtle;
            wss.ClientConnected += new ClientConnectedEventHandler(OnClientConnected);
            wss.Start();
            KeepAlive();




        }

        private void KeepAlive()
        {
            string r = Console.ReadLine();
            while (r != "quit")
            {
                if(r == "users")
                {
                    Console.WriteLine(Users.Count);
                }
                r = Console.ReadLine();
            }
        }



        void OnClientConnected(WebSocketConnection sender, EventArgs e)
        {
            Console.WriteLine("test");
            Users.Add(new User() { Connection = sender });
            sender.Disconnected += new WebSocketDisconnectedEventHandler(OnClientDisconnected);
            sender.DataReceived += new DataReceivedEventHandler(OnClientMessage);

        }

        void OnClientMessage(WebSocketConnection sender, DataReceivedEventArgs e)
        {
            Console.WriteLine(sender);
            User user = Users.Single(a => a.Connection == sender);
            if (e.Data.Contains("/nick"))
            {
                string[] tmpArray = e.Data.Split(new char[] { ' ' });
                if (tmpArray.Length > 1)
                {
                    string myNewName = tmpArray[1];
                    while (Users.Where(a => a.Name == myNewName).Count() != 0)
                    {
                        myNewName += "_";
                    }
                    if (user.Name != null)
                        wss.SendToAll("server: '" + user.Name + "' changed name to '" + myNewName + "'");
                    else
                        sender.Send("you are now know as '" + myNewName + "'");
                    user.Name = myNewName;
                }
            }
            else
            {
                string name = (user.Name == null) ? unknownName : user.Name;
                wss.SendToAllExceptOne(name + ": " + e.Data, sender);
                sender.Send("me: " + e.Data);
            }
        }

        void OnClientDisconnected(WebSocketConnection sender, EventArgs e)
        {
            try
            {

                User user = Users.Single(a => a.Connection == sender);
                string name = (user.Name == null) ? unknownName : user.Name;
                wss.SendToAll("server: "+name + " disconnected");
                Users.Remove(user);
            }
            catch (Exception exc)
            {

                Console.WriteLine("ehm...");
            }

        }
    }
}
我想实现的是首先建立一个成功的websocket连接,并从服务器向我的客户机推送价值

我考虑过Alchemy,但我的版本是Visual Studio express 2010,免费版本,它说“此版本的应用程序不支持解决方案文件夹”


任何帮助都将不胜感激。

如果你仔细看一看,你想要实现的目标会容易得多

它支持高级集线器来实现实时通信,还支持持久连接低级类来对通信进行细粒度控制


支持多种客户端类型,如果在通信的两端都不支持WebSocket,则支持回退(可以选择使用长轮询或永久帧)。

此错误的原因(可能)是因为您没有响应握手。一旦建立连接,浏览器将发送一些数据,服务器必须做出适当响应(否则浏览器将关闭连接)。您可以在上或直接在中阅读更多信息。

我修改了在线下载的代码,下面是我现在得到的:

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Threading;




namespace WebSocketServer
{
    public enum ServerLogLevel { Nothing, Subtle, Verbose };
    public delegate void ClientConnectedEventHandler(WebSocketConnection sender, EventArgs e);

    public class WebSocketServer
    {
        #region private members
        private string webSocketOrigin;     // location for the protocol handshake
        private string webSocketLocation;   // location for the protocol handshake
        #endregion
        static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
        static IPEndPoint ipLocal;

        public event ClientConnectedEventHandler ClientConnected;

        /// <summary>
        /// TextWriter used for logging
        /// </summary>
        public TextWriter Logger { get; set; }     // stream used for logging

        /// <summary>
        /// How much information do you want, the server to post to the stream
        /// </summary>
        public ServerLogLevel LogLevel = ServerLogLevel.Subtle;

        /// <summary>
        /// Gets the connections of the server
        /// </summary>
        public List<WebSocketConnection> Connections { get; private set; }

        /// <summary>
        /// Gets the listener socket. This socket is used to listen for new client connections
        /// </summary>
        public Socket ListenerSocker { get; private set; }

        /// <summary>
        /// Get the port of the server
        /// </summary>
        public int Port { get; private set; }


        public WebSocketServer(int port, string origin, string location)
        {
            Port = port;
            Connections = new List<WebSocketConnection>();
            webSocketOrigin = origin;
            webSocketLocation = location;
        }

        /// <summary>
        /// Starts the server - making it listen for connections
        /// </summary>
        public void Start()
        {
            // create the main server socket, bind it to the local ip address and start listening for clients
            ListenerSocker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            ipLocal = new IPEndPoint(IPAddress.Loopback, Port);
            ListenerSocker.Bind(ipLocal);
            ListenerSocker.Listen(100);



            LogLine(DateTime.Now + "> server stated on " + ListenerSocker.LocalEndPoint, ServerLogLevel.Subtle);

            ListenForClients();
        }

        // look for connecting clients
        private void ListenForClients()
        {
            ListenerSocker.BeginAccept(new AsyncCallback(OnClientConnect), null);
        }

        private void OnClientConnect(IAsyncResult asyn)
        {

            byte[] buffer = new byte[1024];
            string headerResponse = "";

            // create a new socket for the connection
            var clientSocket = ListenerSocker.EndAccept(asyn);
            var i = clientSocket.Receive(buffer);
            headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
            //Console.WriteLine(headerResponse);


            if (clientSocket != null)
            {

                // Console.WriteLine("HEADER RESPONSE:"+headerResponse);
                var key = headerResponse.Replace("ey:", "`")
                              .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                              .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                              .Trim();
                var test1 = AcceptKey(ref key);
                var newLine = "\r\n";
                var name = "Charmaine";
                var response = "HTTP/1.1 101 Switching Protocols" + newLine
                         + "Upgrade: websocket" + newLine
                         + "Connection: Upgrade" + newLine
                         + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                         + "Testing lang naman po:" + name
                         ;

                // which one should I use? none of them fires the onopen method
                clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response));
            }





            // keep track of the new guy
            var clientConnection = new WebSocketConnection(clientSocket);
            Connections.Add(clientConnection);
            // clientConnection.Disconnected += new WebSocketDisconnectedEventHandler(ClientDisconnected);
            Console.WriteLine("New user: " + ipLocal);
            // invoke the connection event
            if (ClientConnected != null)
                ClientConnected(clientConnection, EventArgs.Empty);

            if (LogLevel != ServerLogLevel.Nothing)
                clientConnection.DataReceived += new DataReceivedEventHandler(DataReceivedFromClient);



            // listen for more clients
            ListenForClients();

        }

        void ClientDisconnected(WebSocketConnection sender, EventArgs e)
        {
            Connections.Remove(sender);
            LogLine(DateTime.Now + "> " + sender.ConnectionSocket.LocalEndPoint + " disconnected", ServerLogLevel.Subtle);
        }

        void DataReceivedFromClient(WebSocketConnection sender, DataReceivedEventArgs e)
        {
            Log(DateTime.Now + "> data from " + sender.ConnectionSocket.LocalEndPoint, ServerLogLevel.Subtle);
            Log(": " + e.Data + "\n" + e.Size + " bytes", ServerLogLevel.Verbose);
            LogLine("", ServerLogLevel.Subtle);
        }


        /// <summary>
        /// send a string to all the clients (you spammer!)
        /// </summary>
        /// <param name="data">the string to send</param>
        public void SendToAll(string data)
        {
            Connections.ForEach(a => a.Send(data));
        }

        /// <summary>
        /// send a string to all the clients except one
        /// </summary>
        /// <param name="data">the string to send</param>
        /// <param name="indifferent">the client that doesn't care</param>
        public void SendToAllExceptOne(string data, WebSocketConnection indifferent)
        {
            foreach (var client in Connections)
            {
                if (client != indifferent)
                    client.Send(data);
            }
        }

        /// <summary>
        /// Takes care of the initial handshaking between the the client and the server
        /// </summary>


        private void Log(string str, ServerLogLevel level)
        {
            if (Logger != null && (int)LogLevel >= (int)level)
            {
                Logger.Write(str);
            }
        }

        private void LogLine(string str, ServerLogLevel level)
        {
            Log(str + "\r\n", level);
        }

        private static string AcceptKey(ref string key)
        {
            string longKey = key + guid;
            byte[] hashBytes = ComputeHash(longKey);
            return Convert.ToBase64String(hashBytes);
        }
        static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        private static byte[] ComputeHash(string str)
        {
            return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
        }



        private void ShakeHands(Socket conn)
        {
            using (var stream = new NetworkStream(conn))
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream))
            {
                //read handshake from client (no need to actually read it, we know its there):
                LogLine("Reading client handshake:", ServerLogLevel.Verbose);
                string r = null;
                while (r != "")
                {
                    r = reader.ReadLine();
                    LogLine(r, ServerLogLevel.Verbose);
                }

                // 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: " + webSocketOrigin);
                writer.WriteLine("WebSocket-Location: " + webSocketLocation);
                writer.WriteLine("");
            }


            // tell the nerds whats going on
            LogLine("Sending handshake:", ServerLogLevel.Verbose);
            LogLine("HTTP/1.1 101 Web Socket Protocol Handshake", ServerLogLevel.Verbose);
            LogLine("Upgrade: WebSocket", ServerLogLevel.Verbose);
            LogLine("Connection: Upgrade", ServerLogLevel.Verbose);
            LogLine("WebSocket-Origin: " + webSocketOrigin, ServerLogLevel.Verbose);
            LogLine("WebSocket-Location: " + webSocketLocation, ServerLogLevel.Verbose);
            LogLine("", ServerLogLevel.Verbose);

            LogLine("Started listening to client", ServerLogLevel.Verbose);
            //conn.Listen();
        }


    }
}
使用系统;
使用System.Collections.Generic;
使用System.Net.Sockets;
Net系统;
使用System.IO;
使用System.Security.Cryptography;
使用系统线程;
命名空间WebSocketServer
{
public enum ServerLogLevel{无,微妙,详细};
公共委托void ClientConnectedEventHandler(WebSocketConnection发送方,事件参数e);
公共类WebSocketServer
{
#区域私人成员
私有字符串webSocketOrigin;//协议握手的位置
私有字符串webSocketLocation;//协议握手的位置
#端区
静态专用字符串guid=“258EAFA5-E914-47DA-95CA-C5AB0DC85B11”;
静态IPEndPoint ipLocal;
公共事件客户端已连接EventHandler客户端已连接;
/// 
///用于日志记录的TextWriter
/// 
公共TextWriter记录器{get;set;}//用于记录的流
/// 
///您希望服务器向流发布多少信息
/// 
public ServerLogLevel LogLevel=ServerLogLevel.minute;
/// 
///获取服务器的连接
/// 
公共列表连接{get;private set;}
/// 
///获取侦听器套接字。此套接字用于侦听新的客户端连接
/// 
公共套接字侦听器套接字{get;private set;}
/// 
///获取服务器的端口
/// 
公共int端口{get;私有集;}
公共WebSocketServer(int端口、字符串原点、字符串位置)
{
端口=端口;
连接=新列表();
webSocketOrigin=原点;
webSocketLocation=位置;
}
/// 
///启动服务器-使其侦听连接
/// 
公开作废开始()
{
//创建主服务器套接字,将其绑定到本地ip地址并开始侦听客户端
ListenerSocker=新套接字(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP);
ipLocal=新IPEndPoint(IPAddress.Loopback,端口);
ListenerSocker.Bind(ipLocal);
ListenerSocker.听(100);
日志行(DateTime.Now+“>服务器在“+ListenerSocker.LocalEndPoint,ServerLogLevel.minute”上声明);
ListenForClients();
}
//寻找连接客户端
私有void listenforcients()
{
beginacept(新的异步回调(OnClientConnect),null);
}
客户端连接上的私有无效(IAsyncResult asyn)
{
字节[]缓冲区=新字节[1024];
字符串headerResponse=“”;
//为连接创建一个新套接字
var clientSocket=ListenerSocker.EndAccept(asyn);
var i=clientSocket.Receive(缓冲区);
headerResponse=(System.Text.Encoding.UTF8.GetString(buffer)).Substring(0,i);
//控制台写入线(headerResponse);
if(clientSocket!=null)
{
//Console.WriteLine(“标头响应:+headerResponse”);
var key=headerResponse.Replace(“ey:”,“`”)
.Split('`')[1]//DGHLIHNHBXBSSBUB25JZQ==\r\n。。。。。。。
.Replace(“\r”和“).Split(“\n”)[0]//dGhlIHNhbXBsZSBub25jZQ==
.Trim();
var test1=接受键(ref键);
var newLine=“\r\n”;
var name=“Charmaine”;
var response=“HTTP/1.1 101交换协议”+换行符
+“升级:websocket”+换行符
+“连接:升级”+换行
+“Sec WebSocket接受:”+test1+换行符+换行符
+“测试郎纳曼波:”+名称
;
//我应该使用哪一个?它们都不会触发onopen方法
Send(System.Text.Encoding.UTF8.GetBytes(response));
}
//跟踪那个新来的家伙
var clientConnection=newwebsocketconnection(clientSocket);
Connections.Add(clientConnection);
//clientConnection.Disconnected+=新WebSocketDisconnectedEventHandler(ClientDisconnected);
Console.WriteLine(“新用户:+ipLocal”);
//调用连接
Firefox can't establish a connection to the server at ws://localhost:8080/
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Threading;




namespace WebSocketServer
{
    public enum ServerLogLevel { Nothing, Subtle, Verbose };
    public delegate void ClientConnectedEventHandler(WebSocketConnection sender, EventArgs e);

    public class WebSocketServer
    {
        #region private members
        private string webSocketOrigin;     // location for the protocol handshake
        private string webSocketLocation;   // location for the protocol handshake
        #endregion
        static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
        static IPEndPoint ipLocal;

        public event ClientConnectedEventHandler ClientConnected;

        /// <summary>
        /// TextWriter used for logging
        /// </summary>
        public TextWriter Logger { get; set; }     // stream used for logging

        /// <summary>
        /// How much information do you want, the server to post to the stream
        /// </summary>
        public ServerLogLevel LogLevel = ServerLogLevel.Subtle;

        /// <summary>
        /// Gets the connections of the server
        /// </summary>
        public List<WebSocketConnection> Connections { get; private set; }

        /// <summary>
        /// Gets the listener socket. This socket is used to listen for new client connections
        /// </summary>
        public Socket ListenerSocker { get; private set; }

        /// <summary>
        /// Get the port of the server
        /// </summary>
        public int Port { get; private set; }


        public WebSocketServer(int port, string origin, string location)
        {
            Port = port;
            Connections = new List<WebSocketConnection>();
            webSocketOrigin = origin;
            webSocketLocation = location;
        }

        /// <summary>
        /// Starts the server - making it listen for connections
        /// </summary>
        public void Start()
        {
            // create the main server socket, bind it to the local ip address and start listening for clients
            ListenerSocker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            ipLocal = new IPEndPoint(IPAddress.Loopback, Port);
            ListenerSocker.Bind(ipLocal);
            ListenerSocker.Listen(100);



            LogLine(DateTime.Now + "> server stated on " + ListenerSocker.LocalEndPoint, ServerLogLevel.Subtle);

            ListenForClients();
        }

        // look for connecting clients
        private void ListenForClients()
        {
            ListenerSocker.BeginAccept(new AsyncCallback(OnClientConnect), null);
        }

        private void OnClientConnect(IAsyncResult asyn)
        {

            byte[] buffer = new byte[1024];
            string headerResponse = "";

            // create a new socket for the connection
            var clientSocket = ListenerSocker.EndAccept(asyn);
            var i = clientSocket.Receive(buffer);
            headerResponse = (System.Text.Encoding.UTF8.GetString(buffer)).Substring(0, i);
            //Console.WriteLine(headerResponse);


            if (clientSocket != null)
            {

                // Console.WriteLine("HEADER RESPONSE:"+headerResponse);
                var key = headerResponse.Replace("ey:", "`")
                              .Split('`')[1]                     // dGhlIHNhbXBsZSBub25jZQ== \r\n .......
                              .Replace("\r", "").Split('\n')[0]  // dGhlIHNhbXBsZSBub25jZQ==
                              .Trim();
                var test1 = AcceptKey(ref key);
                var newLine = "\r\n";
                var name = "Charmaine";
                var response = "HTTP/1.1 101 Switching Protocols" + newLine
                         + "Upgrade: websocket" + newLine
                         + "Connection: Upgrade" + newLine
                         + "Sec-WebSocket-Accept: " + test1 + newLine + newLine
                         + "Testing lang naman po:" + name
                         ;

                // which one should I use? none of them fires the onopen method
                clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response));
            }





            // keep track of the new guy
            var clientConnection = new WebSocketConnection(clientSocket);
            Connections.Add(clientConnection);
            // clientConnection.Disconnected += new WebSocketDisconnectedEventHandler(ClientDisconnected);
            Console.WriteLine("New user: " + ipLocal);
            // invoke the connection event
            if (ClientConnected != null)
                ClientConnected(clientConnection, EventArgs.Empty);

            if (LogLevel != ServerLogLevel.Nothing)
                clientConnection.DataReceived += new DataReceivedEventHandler(DataReceivedFromClient);



            // listen for more clients
            ListenForClients();

        }

        void ClientDisconnected(WebSocketConnection sender, EventArgs e)
        {
            Connections.Remove(sender);
            LogLine(DateTime.Now + "> " + sender.ConnectionSocket.LocalEndPoint + " disconnected", ServerLogLevel.Subtle);
        }

        void DataReceivedFromClient(WebSocketConnection sender, DataReceivedEventArgs e)
        {
            Log(DateTime.Now + "> data from " + sender.ConnectionSocket.LocalEndPoint, ServerLogLevel.Subtle);
            Log(": " + e.Data + "\n" + e.Size + " bytes", ServerLogLevel.Verbose);
            LogLine("", ServerLogLevel.Subtle);
        }


        /// <summary>
        /// send a string to all the clients (you spammer!)
        /// </summary>
        /// <param name="data">the string to send</param>
        public void SendToAll(string data)
        {
            Connections.ForEach(a => a.Send(data));
        }

        /// <summary>
        /// send a string to all the clients except one
        /// </summary>
        /// <param name="data">the string to send</param>
        /// <param name="indifferent">the client that doesn't care</param>
        public void SendToAllExceptOne(string data, WebSocketConnection indifferent)
        {
            foreach (var client in Connections)
            {
                if (client != indifferent)
                    client.Send(data);
            }
        }

        /// <summary>
        /// Takes care of the initial handshaking between the the client and the server
        /// </summary>


        private void Log(string str, ServerLogLevel level)
        {
            if (Logger != null && (int)LogLevel >= (int)level)
            {
                Logger.Write(str);
            }
        }

        private void LogLine(string str, ServerLogLevel level)
        {
            Log(str + "\r\n", level);
        }

        private static string AcceptKey(ref string key)
        {
            string longKey = key + guid;
            byte[] hashBytes = ComputeHash(longKey);
            return Convert.ToBase64String(hashBytes);
        }
        static SHA1 sha1 = SHA1CryptoServiceProvider.Create();
        private static byte[] ComputeHash(string str)
        {
            return sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str));
        }



        private void ShakeHands(Socket conn)
        {
            using (var stream = new NetworkStream(conn))
            using (var reader = new StreamReader(stream))
            using (var writer = new StreamWriter(stream))
            {
                //read handshake from client (no need to actually read it, we know its there):
                LogLine("Reading client handshake:", ServerLogLevel.Verbose);
                string r = null;
                while (r != "")
                {
                    r = reader.ReadLine();
                    LogLine(r, ServerLogLevel.Verbose);
                }

                // 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: " + webSocketOrigin);
                writer.WriteLine("WebSocket-Location: " + webSocketLocation);
                writer.WriteLine("");
            }


            // tell the nerds whats going on
            LogLine("Sending handshake:", ServerLogLevel.Verbose);
            LogLine("HTTP/1.1 101 Web Socket Protocol Handshake", ServerLogLevel.Verbose);
            LogLine("Upgrade: WebSocket", ServerLogLevel.Verbose);
            LogLine("Connection: Upgrade", ServerLogLevel.Verbose);
            LogLine("WebSocket-Origin: " + webSocketOrigin, ServerLogLevel.Verbose);
            LogLine("WebSocket-Location: " + webSocketLocation, ServerLogLevel.Verbose);
            LogLine("", ServerLogLevel.Verbose);

            LogLine("Started listening to client", ServerLogLevel.Verbose);
            //conn.Listen();
        }


    }
}
using Alchemy;
using Alchemy.Classes;
namespace GameServer
{
    static class Program
    {
        public static readonly ConcurrentDictionary<ClientPeer, bool> OnlineUsers = new ConcurrentDictionary<ClientPeer, bool>();
        static void Main(string[] args)
        {
            var aServer = new WebSocketServer(4530, IPAddress.Any)
            {
                OnReceive = context => OnReceive(context),
                OnConnected = context => OnConnect(context),
                OnDisconnect = context => OnDisconnect(context),
                TimeOut = new TimeSpan(0, 10, 0),
                FlashAccessPolicyEnabled = true
            };
        }
        private static void OnConnect(UserContext context)
        {
            var client = new ClientPeer(context);
            OnlineUsers.TryAdd(client, false);
            //Do something with the new client
        }
    }
}
private void ShakeHands(Socket conn)
    {
        using (var stream = new NetworkStream(conn))
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        {
            //read handshake from client (no need to actually read it, we know its there):
            LogLine("Reading client handshake:", ServerLogLevel.Verbose);
            string r = null;
            Dictionary<string, string> headers = new Dictionary<string, string>();
            while (r != "")
            {
                r = reader.ReadLine();
                string[] tokens = r.Split(new char[] { ':' }, 2);
                if (!string.IsNullOrWhiteSpace(r) && tokens.Length > 1)
                {
                    headers[tokens[0]] = tokens[1].Trim();
                }
                LogLine(r, ServerLogLevel.Verbose);
            }


            //string line = string.Empty;
            //while ((line = reader.ReadLine()) != string.Empty)
            //{
            //    string[] tokens = line.Split(new char[] { ':' }, 2);
            //    if (!string.IsNullOrWhiteSpace(line) && tokens.Length > 1)
            //    {
            //        headers[tokens[0]] = tokens[1].Trim();
            //    }
            //}

            string responseKey = "";
            string key = string.Concat(headers["Sec-WebSocket-Key"], "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
            using (SHA1 sha1 = SHA1.Create())
            {
                byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(key));
                responseKey = Convert.ToBase64String(hash);
            }



            // 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: " + webSocketOrigin);
            writer.WriteLine("WebSocket-Location: " + webSocketLocation);
            //writer.WriteLine("Sec-WebSocket-Protocol: chat");
            writer.WriteLine("Sec-WebSocket-Accept: " + responseKey);
            writer.WriteLine("");
        }


        // tell the nerds whats going on
        LogLine("Sending handshake:", ServerLogLevel.Verbose);
        LogLine("HTTP/1.1 101 Web Socket Protocol Handshake", ServerLogLevel.Verbose);
        LogLine("Upgrade: WebSocket", ServerLogLevel.Verbose);
        LogLine("Connection: Upgrade", ServerLogLevel.Verbose);
        LogLine("WebSocket-Origin: " + webSocketOrigin, ServerLogLevel.Verbose);
        LogLine("WebSocket-Location: " + webSocketLocation, ServerLogLevel.Verbose);
        LogLine("", ServerLogLevel.Verbose);

        LogLine("Started listening to client", ServerLogLevel.Verbose);
        //conn.Listen();
    }