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 = 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 = 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); } }
public void Send(string message) { foreach (SocketConnection item in connectionSocketList) { logger.Log("发送的消息: " + message); if (!item.ConnectionSocket.Connected) return; try { if (item.IsDataMasked) { DataFrame dr = new DataFrame(message); item.ConnectionSocket.Send(dr.GetBytes()); } else { item.ConnectionSocket.Send(FirstByte); item.ConnectionSocket.Send(Encoding.UTF8.GetBytes(message)); item.ConnectionSocket.Send(LastByte); } } catch (Exception ex) { logger.Log(ex.Message); } } }