public void StartServer() { Char char1 = Convert.ToChar(65533); IPAddress ipAddress = getLocalmachineIPAddress(); Listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); Listener.Bind(new IPEndPoint(ipAddress, ServerPort)); Listener.Listen(ConnectionsQueueLength); _logger.Log(string.Format("聊天服务器启动。监听地址:{0}, 端口:{1}", ipAddress, ServerPort)); _logger.Log(string.Format("WebSocket服务器地址: ws://{0}:{1}/chat", ipAddress, ServerPort)); while (true) { Socket sc = Listener.Accept(); if (sc != null) { System.Threading.Thread.Sleep(100); SocketConnection socketConn = new SocketConnection(); socketConn.ConnectionSocket = sc; socketConn.NewConnection += new NewConnection_EventHandler(socketConn_NewConnection); socketConn.DataReceived += new DataReceived_EventHandler(socketConn_BroadcastMessage); socketConn.Disconnected += new Disconnected_EventHandler(socketConn_Disconnected); //异步读取消息 socketConn.ConnectionSocket.BeginReceive(socketConn.receivedDataBuffer, 0, socketConn.receivedDataBuffer.Length, 0, new AsyncCallback(socketConn.ManageHandshake), //CallBack socketConn.ConnectionSocket.Available); connectionSocket_List.Add(socketConn); } } }
private void Read(IAsyncResult status) { if (!ConnectionSocket.Connected) { return; } string messageReceived = string.Empty; DataFrame dr = new DataFrame(receivedDataBuffer); try { if (!this.isDataMasked) { // Web Socket protocol: messages are sent with 0x00 and 0xFF as padding bytes System.Text.UTF8Encoding decoder = _CacheSetting.cacheUtf8Encoding ? null : new System.Text.UTF8Encoding(); int startIndex = 0; int endIndex = 0; // Search for the start byte while (receivedDataBuffer[startIndex] == FirstByte[0]) { startIndex++; } // Search for the end byte endIndex = startIndex + 1; while (receivedDataBuffer[endIndex] != LastByte[0] && endIndex != MaxBufferSize - 1) { endIndex++; } if (endIndex == MaxBufferSize - 1) { endIndex = MaxBufferSize; } // Get the message messageReceived = (_CacheSetting.cacheUtf8Encoding ? _CacheSetting.utf8Encoding : decoder).GetString(receivedDataBuffer, startIndex, endIndex - startIndex); } else { messageReceived = dr.Text; } if ((messageReceived.Length == MaxBufferSize && messageReceived[0] == Convert.ToChar(65533)) || messageReceived.Length == 0) { _logger.Log("接受到的信息 [\"" + string.Format("logout:{0}", this.name) + "\"]"); if (Disconnected != null) { Disconnected(this, EventArgs.Empty); } } else { if (DataReceived != null) { _logger.Log("接受到的信息 [\"" + messageReceived + "\"]"); DataReceived(this, messageReceived, EventArgs.Empty); } Array.Clear(receivedDataBuffer, 0, receivedDataBuffer.Length); ConnectionSocket.BeginReceive(receivedDataBuffer, 0, receivedDataBuffer.Length, 0, new AsyncCallback(Read), null); } } catch (Exception ex) { _logger.Log(ex.Message); _logger.Log("Socket连接将会被终止。"); if (Disconnected != null) { Disconnected(this, EventArgs.Empty); } } }