Пример #1
0
 public void SendToAllExceptSelf(String data, WebSocketConnection self)
 {
     _connections.Where(c => c != self).ToList().ForEach(c => c.Send(data));
 }
Пример #2
0
        /// <summary>
        /// 進行HandShake
        /// </summary>
        /// <param name="socket"></param>
        private void ShakeHands(Socket socket)
        {
            // 存放Request資料的Buffer
            byte[] buffer = new byte[2048];
            // 接收的Request長度
            var length = socket.Receive(buffer);
            // 將buffer中的資料解碼成字串
            var data = Encoding.UTF8.GetString(buffer, 0, length);
            Console.WriteLine(data);

            // 將資料字串中的空白位元移除
            var dataArray = data.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            if (dataArray.Count() == 0) {
                return;
            }

            // 從Client傳來的Request Header訊息中取
            var key = dataArray.Where(s => s.Contains("Sec-WebSocket-Key: ")).Single().Replace("Sec-WebSocket-Key: ", String.Empty).Trim();
            var acceptKey = CreateAcceptKey(key);
            // WebSocket Protocol定義的ShakeHand訊息
            var handShakeMsg =
                "HTTP/1.1 101 Switching Protocols\r\n" +
                "Upgrade: websocket\r\n" +
                "Connection: Upgrade\r\n" +
                "Sec-WebSocket-Accept: " + acceptKey + "\r\n\r\n";

            socket.Send(Encoding.UTF8.GetBytes(handShakeMsg));

            Console.WriteLine(handShakeMsg);
            // 產生WebSocketConnection實體並加入佇列中管理
            var clientConn = new WebSocketConnection(socket);
            _connections.Add(clientConn);
            // 註冊Disconnected事件
            clientConn.OnDisconnected += new ClientDisconnectedEventHandler(DisconnectedWork);

            // 確認Connection是否繼續存在,並持續監聽
            if (OnConnected != null)
                OnConnected(clientConn, EventArgs.Empty);
            _serverSocket.BeginAccept(new AsyncCallback(onConnect), null);
        }
Пример #3
0
 /// <summary>
 /// DisConnected事件
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="ev"></param>
 private void DisconnectedWork(WebSocketConnection sender, EventArgs ev)
 {
     _connections.Remove(sender);
     sender.Close();
 }
Пример #4
0
 static void DoDataReceivedWork(WebSocketConnection sender, DataReceivedEventArgs ev)
 {
     _server.SendToAllClient(ev.Data);
 }
Пример #5
0
 static void DoConnectedWork(WebSocketConnection sender, EventArgs ev)
 {
     sender.OnDataReceived += new DataReceivedEventHandler(DoDataReceivedWork);
     sender.OnDisconnected += new ClientDisconnectedEventHandler(DoClientDisconnectedWork);
 }
Пример #6
0
 static void DoClientDisconnectedWork(WebSocketConnection sender, EventArgs ev)
 {
     _server.SendToAllClient("Someone leave the room");
 }