public void ServerSendData(uint clientIndex, string dataToSend) { if (_server.ClientConnected(clientIndex) && dataToSend != null && dataToSend.Length > 0) { _server.SendDataAsync(clientIndex, Encoding.ASCII.GetBytes(dataToSend), dataToSend.Length, Server_SendDataCallback); } }
private static void SendDataAsync(string dataToSend) { try { byte[] SendData = System.Text.Encoding.ASCII.GetBytes(dataToSend); for (uint index = 1; index <= tcpServer.NumberOfClientsConnected; index++) { if (debug > 0) { CrestronConsole.Print("\n Catch Connect SendDataAsync attempt for index: " + index); } if (tcpServer.ClientConnected(index)) { SocketErrorCodes resultCodes = tcpServer.SendDataAsync(index, SendData, SendData.Length, OnTCPServerSendCallback); if (debug > 0) { CrestronConsole.Print("\n Catch Connect SendDataAsync resultCodes: " + resultCodes.ToString()); } } else { CrestronConsole.Print("\n Catch Connect SendDataAsync client not connected at index: " + index); } } } catch (Exception e) { ErrorLog.Error("error = " + e.Message); } }
/// <summary> /// Unsecure TCP Client Connected to Unsecure Server Callback /// </summary> /// <param name="myTCPServer"></param> /// <param name="clientIndex"></param> void UnsecureConnectCallback(TCPServer myTCPServer, uint clientIndex) { if (myTCPServer.ClientConnected(clientIndex)) { if (SharedKeyRequired) { byte[] b = Encoding.GetEncoding(28591).GetBytes(SharedKey + "\n"); myTCPServer.SendDataAsync(clientIndex, b, b.Length, UnsecureSendDataAsyncCallback); Debug.Console(2, "Sent Shared Key to client at {0}", myTCPServer.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex)); } if (HeartbeatRequired) { CTimer HeartbeatTimer = new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs); HeartbeatTimerDictionary.Add(clientIndex, HeartbeatTimer); } myTCPServer.ReceiveDataAsync(clientIndex, UnsecureReceivedDataAsyncCallback); if (myTCPServer.State != ServerState.SERVER_LISTENING && MaxClients > 1 && !ServerStopped) { myTCPServer.WaitForConnectionAsync(IPAddress.Any, UnsecureConnectCallback); } } if (myTCPServer.State != ServerState.SERVER_LISTENING && MaxClients > 1 && !ServerStopped) { myTCPServer.WaitForConnectionAsync(IPAddress.Any, UnsecureConnectCallback); } }
private void Server_RecieveDataCallBack(TCPServer s, uint newClientIndex, int numberOfBytesReceived) { // CrestronConsole.PrintLine("Server> NumberOfBytesReceived[{0}] from Client[{1}]", numberOfBytesReceived, newClientIndex); if (numberOfBytesReceived > 0) { _totalBytesReceived += numberOfBytesReceived; //#if Debug CrestronConsole.PrintLine("ReceiveDataCallBack: client: [{0}] length: [{1}]", newClientIndex, numberOfBytesReceived); //#endif byte[] recvd_bytes = new byte[numberOfBytesReceived]; Array.Copy(s.GetIncomingDataBufferForSpecificClient(newClientIndex), recvd_bytes, numberOfBytesReceived); //ServerTcpReceive(ASCIIEncoding.ASCII.GetString(recvd_bytes, 0, numberOfBytesReceived)); while (s.ClientConnected(newClientIndex)) { numberOfBytesReceived = s.ReceiveData(newClientIndex); if (numberOfBytesReceived > 0) { _totalBytesReceived += numberOfBytesReceived; //#if Debug CrestronConsole.PrintLine("ReceiveDataCallBack: client: [{0}] length: [{1}]", newClientIndex, numberOfBytesReceived); //#endif recvd_bytes = new byte[numberOfBytesReceived]; Array.Copy(s.GetIncomingDataBufferForSpecificClient(newClientIndex), recvd_bytes, numberOfBytesReceived); //ServerTcpReceive(ASCIIEncoding.ASCII.GetString(recvd_bytes, 0, numberOfBytesReceived)); } else { s.ReceiveDataAsync(newClientIndex, Server_RecieveDataCallBack); break; } } } }
public void Read(TCPServer myTCPServer, uint clientIndex, int numberOfBytesReceived) { if (!myTCPServer.ClientConnected(clientindex)) { return; } string messageReceived = string.Empty; byte[] readBuffer = new byte[numberOfBytesReceived]; Array.Copy(myTCPServer.GetIncomingDataBufferForSpecificClient(clientindex), readBuffer, numberOfBytesReceived); try { messageReceived = Encoding.GetEncoding(28591).GetString(readBuffer, 0, readBuffer.Length); if (DataReceived != null) { DataReceived(this, messageReceived, EventArgs.Empty); } Array.Clear(readBuffer, 0, readBuffer.Length); myTCPServer.ReceiveDataAsync(clientindex, this.Read, 0); } catch (Exception) { if (Disconnected != null) { Disconnected(this, EventArgs.Empty); } } }
public void NotifyClients(string data) { byte[] buffer = Encoding.ASCII.GetBytes(data); try { new Thread((o) => { foreach (var client in clients) { if (server.ClientConnected(client.Key)) { server.SendDataAsync(client.Key, buffer, buffer.Length, null); } else { ErrorLog.Notice("Client {0} Disconnection Status: {1}", client.Key, server.Disconnect(client.Key)); clients.Remove(client.Key); } } return(clients); }, null); } catch (Exception ex) { ErrorLog.Notice("Something Went Wrong While Trying To Send Data To Client\r\n{1}", ex.Message); } }
private void Server_RecieveDataCallBack(TCPServer s, uint clientIndex, int numberOfBytesReceived) { CrestronConsole.PrintLine("Server> NumberOfBytesReceived[{0}] from Client[{1}]", numberOfBytesReceived, clientIndex); if (numberOfBytesReceived > 0) { #if Debug CrestronConsole.PrintLine("ReceiveDataCallBack: client: [{0}] length: [{1}]", clientIndex, numberOfBytesReceived); #endif _serverOnDataReceived(null, new ServerTcpReceiveEventArgs(clientIndex, s.GetIncomingDataBufferForSpecificClient(clientIndex).Take(numberOfBytesReceived).ToArray())); while (s.ClientConnected(clientIndex)) { numberOfBytesReceived = s.ReceiveData(clientIndex); if (numberOfBytesReceived > 0) { #if Debug CrestronConsole.PrintLine("ReceiveDataCallBack: client: [{0}] length: [{1}]", clientIndex, numberOfBytesReceived); #endif _serverOnDataReceived(null, new ServerTcpReceiveEventArgs(clientIndex, s.GetIncomingDataBufferForSpecificClient(clientIndex).Take(numberOfBytesReceived).ToArray())); } else { s.ReceiveDataAsync(clientIndex, Server_RecieveDataCallBack); break; } } } }
public void OnClientConnect(TCPServer myTCPServer, uint clientIndex) { if (myTCPServer.ClientConnected(clientIndex)) { SocketConnection socketConn = new SocketConnection(); socketConn.clientindex = clientIndex; socketConn.ConnectionSocket = myTCPServer; socketConn.NewConnection += new NewConnectionEventHandler(socketConn_NewConnection); socketConn.DataReceived += new DataReceivedEventHandler(socketConn_BroadcastMessage); socketConn.Disconnected += new DisconnectedEventHandler(socketConn_Disconnected); socketConn.Log += this.Log; myTCPServer.ReceiveDataAsync(clientIndex, socketConn.ManageHandshake, 0); connectionSocketList.Add(socketConn); } try { SocketErrorCodes codes = Listener.WaitForConnectionAsync(this.OnClientConnect); } catch (Exception ex) { if (this.Log != null) { this.Log(ex.Message); } // logger.Log(ex.Message); } this.Log(string.Format("Client Index {0} Connected", clientIndex)); }
public void ServerSendDataToEveryone(string dataToSend) { foreach (DictionaryEntry client in _clientList) { if (server.ClientConnected((client.Value as Connection).ClientIndex) && dataToSend != null && dataToSend.Length > 0) { byte[] numArray = WebsocketUtil.EncodeMsg((byte)129, StringUtil.toByteArray(dataToSend)); server.SendDataAsync((client.Value as Connection).ClientIndex, numArray, numArray.Length, Server_SendDataCallback); } } }
private void tcpServerClientConnectCallback(TCPServer myTCPServer, uint clientIndex) { CrestronConsole.PrintLine("Server> Incoming Connection: [{0}] :: SocketStatus: {1}", clientIndex, myTCPServer.GetServerSocketStatusForSpecificClient(clientIndex)); if (myTCPServer.ClientConnected(clientIndex)) { Connection newConnection = new Connection(myTCPServer, clientIndex); _clientList.Add(clientIndex, newConnection); // check if needing to wait for a new connection this.CheckForWaitingConnection(); } }
private void Server_ClientConnectCallback(TCPServer s, uint clientIndex) { CrestronConsole.PrintLine("Server> Incoming Connection: [{0}|{1}/{2}] :: SocketStatus: {3}", clientIndex, _numberOfClientsConnected, s.MaxNumberOfClientSupported, s.GetServerSocketStatusForSpecificClient(clientIndex)); if (s.ClientConnected(clientIndex)) { Connection newConnection = new Connection(s, clientIndex); _numberOfClientsConnected++; _clientList.Add(clientIndex, newConnection); // check if needing to wait for a new connection this.CheckForWaitingConnection(); } }
public void OnClientConnect(TCPServer myTCPServer, uint clientIndex) { if (myTCPServer.ClientConnected(clientIndex)) { TCPConnectionClient socketConn = new TCPConnectionClient(); socketConn.clientindex = clientIndex; socketConn.ConnectionSocket = myTCPServer; socketConn.DataReceived += new DataReceivedEventHandler(socketConn_DataReceived); socketConn.Disconnected += new DisconnectedEventHandler(socketConn_Disconnected); myTCPServer.ReceiveDataAsync(clientIndex, socketConn.Read, 0); connectionClienttList.Add(socketConn); //ClientConnected clientIndex } }
public void OnClientConnect(TCPServer myTCPServer, uint clientIndex) { if (myTCPServer.ClientConnected(clientIndex)) { SocketConnection socketConn = new SocketConnection(); socketConn.clientindex = clientIndex; socketConn.ConnectionSocket = myTCPServer; socketConn.NewConnection += new NewConnectionEventHandler(socketConn_NewConnection); socketConn.DataReceived += new DataReceivedEventHandler(socketConn_BroadcastMessage); socketConn.Disconnected += new DisconnectedEventHandler(socketConn_Disconnected); myTCPServer.ReceiveDataAsync(clientIndex, socketConn.Read, 0); connectionSocketList.Add(socketConn); //ClientConnected clientIndex } }
public void OnClientConnect(TCPServer myTCPServer, uint clientIndex) { if (myTCPServer.ClientConnected(clientIndex)) { SocketConnection socketConn = new SocketConnection(); socketConn.clientindex = clientIndex; socketConn.ConnectionSocket = myTCPServer; socketConn.NewConnection += new NewConnectionEventHandler(socketConn_NewConnection); socketConn.DataReceived += new DataReceivedEventHandler(socketConn_BroadcastMessage); socketConn.Disconnected += new DisconnectedEventHandler(socketConn_Disconnected); socketConn.Log += this.Log; myTCPServer.ReceiveDataAsync(clientIndex, socketConn.ManageHandshake, 0); connectionSocketList.Add(socketConn); //ClientConnected clientIndex } this.Log(string.Format("Client Index {0} Connected", clientIndex)); }
private static void OnTCPServerClientConnectCallback(TCPServer myTCPServer, uint clientIndex) { if (debug > 0) { CrestronConsole.Print("\n Catch Connect OnTCPServerClientConnectCallback index: " + clientIndex.ToString()); } //Listen for data from the connected client if (myTCPServer.ClientConnected(clientIndex)) { SocketErrorCodes resultCodes = myTCPServer.ReceiveDataAsync(clientIndex, OnTCPReceiveCallback); if (debug > 0) { CrestronConsole.Print("\n Catch Connect OnTCPServerClientConnectCallback ReceiveDataAsync resultCodes: " + resultCodes.ToString()); } } else { if (debug > 0) { CrestronConsole.Print("\n Catch Connect OnTCPServerClientConnectCallback client not connected at: " + clientIndex); } } //Listen for other connections if (myTCPServer.MaxNumberOfClientSupported > myTCPServer.NumberOfClientsConnected) { try { SocketErrorCodes connectionResultCodes = myTCPServer.WaitForConnectionAsync("0.0.0.0", OnTCPServerClientConnectCallback); if (debug > 0) { CrestronConsole.Print("\n Catch Connect TCPServer OnTCPServerClientConnectCallback WaitForConnectionAsync resultCodes: " + connectionResultCodes.ToString()); } } catch (Exception e) { ErrorLog.Error("\n Catch Connect OnTCPServerClientConnectCallback WaitForConnectionAsync Exception: " + e.Message); } } }
private void Server_ClientConnectCallback(TCPServer s, uint clientIndex) { CrestronConsole.PrintLine("Server> Incoming Connection: [{0}|{1}/{2}] :: SocketStatus: {3}", clientIndex, _numberOfClientsConnected, s.MaxNumberOfClientSupported, s.GetServerSocketStatusForSpecificClient(clientIndex)); if (s.ClientConnected(clientIndex)) { _numberOfClientsConnected++; // check if needing to wait for a new connection this.CheckForWaitingConnection(); s.ReceiveDataAsync(clientIndex, Server_RecieveDataCallBack); /* * _numberOfClientsConnected--; * CrestronConsole.PrintLine("Server> Disconnect {0}", clientIndex); * * if (!_waiting) * this.CheckForWaitingConnection(); */ } }
public void Read(TCPServer myTCPServer, uint clientIndex, int numberOfBytesReceived) { if (!myTCPServer.ClientConnected(clientindex)) { return; } string messageReceived = string.Empty; try { messageReceived = Encoding.GetEncoding(28591).GetString(myTCPServer.GetIncomingDataBufferForSpecificClient(clientindex), 0, numberOfBytesReceived); DataReceived(this, messageReceived, EventArgs.Empty); myTCPServer.ReceiveDataAsync(clientindex, this.Read, 0); } catch (Exception ex) { if (Disconnected != null) { Disconnected(this, EventArgs.Empty); } } }
/// <summary> /// Disconnect All Clients /// </summary> public void DisconnectAllClientsForShutdown() { Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Disconnecting All Clients"); if (myTcpServer != null) { myTcpServer.SocketStatusChange -= TcpServer_SocketStatusChange; foreach (var index in ConnectedClientsIndexes.ToList()) // copy it here so that it iterates properly { var i = index; if (!myTcpServer.ClientConnected(index)) { continue; } try { myTcpServer.Disconnect(i); Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Disconnected client index: {0}", i); } catch (Exception ex) { Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error Disconnecting client index: {0}. Error: {1}", i, ex); } } Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Server Status: {0}", myTcpServer.ServerSocketStatus); } Debug.Console(2, this, Debug.ErrorLogLevel.Notice, "Disconnected All Clients"); ConnectedClientsIndexes.Clear(); if (!ProgramIsStopping) { OnConnectionChange(); OnServerStateChange(myTcpServer.State); //State shows both listening and connected } // var o = new { }; }
/// <summary> /// The callback for receiving data from the insecure server client. /// </summary> /// <param name="server">The server the callback is executed on.</param> /// <param name="clientIndex">The index of the client data is received from.</param> /// <param name="count">The number of bytes of data received.</param> private void ReceiveDataCallback(TCPServer server, uint clientIndex, int count) { if (count <= 0) { if (server.ClientConnected(clientIndex)) { server.ReceiveDataAsync(clientIndex, ReceiveDataCallback); } return; } var dataBuffer = server.GetIncomingDataBufferForSpecificClient(clientIndex); var data = Encoding.UTF8.GetString(dataBuffer, 0, count); if (Regex.IsMatch(data, "^GET", RegexOptions.IgnoreCase)) { var key = Regex.Match(data, "Sec-WebSocket-Key: (.*)").Groups[1].Value.Trim(); key = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; byte[] keySha1 = Crestron.SimplSharp.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(key)); string sha64 = Convert.ToBase64String(keySha1); var responseMessage = "HTTP/1.1 101 Switching Protocols\r\n" + "Connection: Upgrade\r\n" + "Upgrade: websocket\r\n" + "Sec-WebSocket-Accept: " + sha64 + "\r\n\r\n"; this.Send(responseMessage, clientIndex, false); } else { CrestronConsole.PrintLine("Received '{0}' bytes.", count); bool fin = (dataBuffer[0] & 128) != 0; bool mask = (dataBuffer[1] & 128) != 0; int opcode = dataBuffer[0] & 15; ulong dataLength = (ulong)(dataBuffer[1] - 128); ulong offset = 2; if (opcode == 0x0) { CrestronConsole.PrintLine("Received continuation frame opcode."); } else if (opcode == 0x1) { CrestronConsole.PrintLine("Received text frame opcode."); } else if (opcode == 0x2) { CrestronConsole.PrintLine("Received binary frame opcode."); } else if (opcode >= 0x3 && opcode <= 0x7) { CrestronConsole.PrintLine("Received reserved non-control opcode."); } else if (opcode == 0x8) { this.Send(new byte[] { BitConverter.GetBytes(0x88)[0], BitConverter.GetBytes(0x00)[0] }, clientIndex, false); server.Disconnect(clientIndex); CrestronConsole.PrintLine("Received disconnect OpCode. Disconnected."); return; } else if (opcode == 0x9) { this.Send(new byte[] { BitConverter.GetBytes(0x8A)[0], BitConverter.GetBytes(0x00)[0] }, clientIndex, false); CrestronConsole.PrintLine("Received Ping and sent a Pong."); if (server.ClientConnected(clientIndex)) { server.ReceiveDataAsync(clientIndex, ReceiveDataCallback); } return; } else if (opcode == 0xA) { CrestronConsole.PrintLine("Received Pong."); if (server.ClientConnected(clientIndex)) { server.ReceiveDataAsync(clientIndex, ReceiveDataCallback); } return; } else if (opcode >= 0xB && opcode <= 0xF) { CrestronConsole.PrintLine("Received reserved control frame opcode."); } if (dataLength == 126) { CrestronConsole.PrintLine("Data length is 126."); dataLength = BitConverter.ToUInt16(new byte[] { dataBuffer[3], dataBuffer[2] }, 0); offset = 4; } else if (dataLength == 127) { CrestronConsole.PrintLine("Data length is 127."); dataLength = BitConverter.ToUInt64(new byte[] { dataBuffer[9], dataBuffer[8], dataBuffer[7], dataBuffer[6], dataBuffer[5], dataBuffer[4], dataBuffer[3], dataBuffer[2] }, 0); offset = 10; } if (dataLength == 0) { CrestronConsole.PrintLine("Data length was zero."); this.Send(string.Format("{0}>", InitialParametersClass.ControllerPromptName), clientIndex, true); } else if (mask) { byte[] de = new byte[dataLength]; byte[] mk = new byte[4] { dataBuffer[offset], dataBuffer[offset + 1], dataBuffer[offset + 2], dataBuffer[offset + 3] }; offset += 4; for (ulong i = 0; i < dataLength; i++) { de[i] = (byte)(dataBuffer[offset + i] ^ mk[i % 4]); } var text = Encoding.UTF8.GetString(de, 0, de.Length); var dr = DataReceived; if (dr != null) { dr.Invoke(text, clientIndex); } } else { CrestronConsole.PrintLine("Data length was '{0}', but mask bit not set. Invalid message received.", dataLength); } } if (server.ClientConnected(clientIndex)) { server.ReceiveDataAsync(clientIndex, ReceiveDataCallback); } }
/// <summary> /// Secure TCP Client Connected to Secure Server Callback /// </summary> /// <param name="mySecureTCPServer"></param> /// <param name="clientIndex"></param> void TcpConnectCallback(TCPServer server, uint clientIndex) { try { Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "ConnectCallback: IPAddress: {0}. Index: {1}. Status: {2}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex), clientIndex, server.GetServerSocketStatusForSpecificClient(clientIndex)); if (clientIndex != 0) { if (server.ClientConnected(clientIndex)) { if (!ConnectedClientsIndexes.Contains(clientIndex)) { ConnectedClientsIndexes.Add(clientIndex); } if (SharedKeyRequired) { if (!WaitingForSharedKey.Contains(clientIndex)) { WaitingForSharedKey.Add(clientIndex); } byte[] b = Encoding.GetEncoding(28591).GetBytes("SharedKey:"); server.SendDataAsync(clientIndex, b, b.Length, (x, y, z) => { }); Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Sent Shared Key Request to client at {0}", server.GetAddressServerAcceptedConnectionFromForSpecificClient(clientIndex)); } else { OnServerClientReadyForCommunications(clientIndex); } if (HeartbeatRequired) { if (!HeartbeatTimerDictionary.ContainsKey(clientIndex)) { HeartbeatTimerDictionary.Add(clientIndex, new CTimer(HeartbeatTimer_CallbackFunction, clientIndex, HeartbeatRequiredIntervalMs)); } } server.ReceiveDataAsync(clientIndex, TcpServerReceivedDataAsyncCallback); } } else { Debug.Console(1, this, Debug.ErrorLogLevel.Error, "Client attempt faulty."); if (!ServerStopped) { server.WaitForConnectionAsync(IPAddress.Any, TcpConnectCallback); return; } } } catch (Exception ex) { Debug.Console(2, this, Debug.ErrorLogLevel.Error, "Error in Socket Status Connect Callback. Error: {0}", ex); } //Debug.Console(1, this, Debug.ErrorLogLevel, "((((((Server State bitfield={0}; maxclient={1}; ServerStopped={2}))))))", // server.State, // MaxClients, // ServerStopped); if ((server.State & ServerState.SERVER_LISTENING) != ServerState.SERVER_LISTENING && MaxClients > 1 && !ServerStopped) { Debug.Console(1, this, Debug.ErrorLogLevel.Notice, "Waiting for next connection"); server.WaitForConnectionAsync(IPAddress.Any, TcpConnectCallback); } }
//void ReceivedCallBack(TCPServer myTCPServer, uint clientIndex, int numberOfBytesReceived) public void ManageHandshake(TCPServer myTCPServer, uint clientIndex, int numberOfBytesReceived) { if (myTCPServer.ClientConnected(clientindex)) { string header = "Sec-WebSocket-Version:"; int HandshakeLength = numberOfBytesReceived;// myTCPServer.IncomingDataBuffer.Length;// (int)status.AsyncState; byte[] last8Bytes = new byte[8]; //Encoding.UTF8 decoder = new System.Text.UTF8Encoding(); byte[] receivedbytes = myTCPServer.GetIncomingDataBufferForSpecificClient(clientindex); String rawClientHandshake = Encoding.GetEncoding(28591).GetString(receivedbytes, 0, HandshakeLength); Array.Copy(receivedbytes, HandshakeLength - 8, last8Bytes, 0, 8); //现在使用的是比较新的Websocket协议 if (rawClientHandshake.IndexOf(header) != -1) { this.isDataMasked = true; // string[] rawClientHandshakeLines = rawClientHandshake.Split(new string[] { Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries); string acceptKey = ""; // string key = string.Empty; System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n"); //查找"Abc" System.Text.RegularExpressions.Match m = r.Match(rawClientHandshake); //设定要查找的字符串 if (m.Groups.Count != 0) { acceptKey = System.Text.RegularExpressions.Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim(); } acceptKey = ComputeWebSocketHandshakeSecurityHash09(acceptKey); New_Handshake = string.Format(New_Handshake, acceptKey); byte[] newHandshakeText = Encoding.GetEncoding(28591).GetBytes(New_Handshake); myTCPServer.SendDataAsync(clientindex, newHandshakeText, 0, newHandshakeText.Length, HandshakeFinished, null); return; } string ClientHandshake = Encoding.GetEncoding(28591).GetString(myTCPServer.GetIncomingDataBufferForSpecificClient(clientindex), 0, HandshakeLength - 8); System.Text.RegularExpressions.Regex r1 = new System.Text.RegularExpressions.Regex(@"Sec\-WebSocket\-Key1:(.*?)\r\n"); //查找"Abc" System.Text.RegularExpressions.Match m1 = r1.Match(rawClientHandshake); //设定要查找的字符串 if (m1.Groups.Count != 0) { BuildServerPartialKey(1, System.Text.RegularExpressions.Regex.Replace(m1.Value, @"Sec\-WebSocket\-Key1:(.*?)\r\n", "$1").Trim()); } System.Text.RegularExpressions.Regex r2 = new System.Text.RegularExpressions.Regex(@"Sec\-WebSocket\-Key1:(.*?)\r\n"); //查找"Abc" System.Text.RegularExpressions.Match m2 = r2.Match(rawClientHandshake); //设定要查找的字符串 if (m2.Groups.Count != 0) { BuildServerPartialKey(2, System.Text.RegularExpressions.Regex.Replace(m2.Value, @"Sec\-WebSocket\-Key1:(.*?)\r\n", "$1").Trim()); } System.Text.RegularExpressions.Regex r3 = new System.Text.RegularExpressions.Regex(@"Origin:(.*?)\r\n"); //查找"Abc" System.Text.RegularExpressions.Match m3 = r3.Match(rawClientHandshake); //设定要查找的字符串 if (m3.Groups.Count != 0) { Handshake = string.Format(Handshake, System.Text.RegularExpressions.Regex.Replace(m3.Value, @"Origin:(.*?)\r\n", "$1").Trim()); } else { Handshake = string.Format(Handshake, "null"); } // string[] ClientHandshakeLines = ClientHandshake.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // logger.Log("新的连接请求来自" + ConnectionSocket.LocalEndPoint + "。正在准备连接 ..."); // Welcome the new client //foreach (string Line in ClientHandshakeLines) //{ // logger.Log(Line); // if (Line.Contains("Sec-WebSocket-Key1:")) // BuildServerPartialKey(1, Line.Substring(Line.IndexOf(":") + 2)); // if (Line.Contains("Sec-WebSocket-Key2:")) // BuildServerPartialKey(2, Line.Substring(Line.IndexOf(":") + 2)); // if (Line.Contains("Origin:")) // try // { // Handshake = string.Format(Handshake, Line.Substring(Line.IndexOf(":") + 2)); // } // catch // { // Handshake = string.Format(Handshake, "null"); // } //} //// Build the response for the client byte[] HandshakeText = Encoding.UTF8.GetBytes(Handshake); byte[] serverHandshakeResponse = new byte[HandshakeText.Length + 16]; byte[] serverKey = BuildServerFullKey(last8Bytes); Array.Copy(HandshakeText, serverHandshakeResponse, HandshakeText.Length); Array.Copy(serverKey, 0, serverHandshakeResponse, HandshakeText.Length, 16); //logger.Log("发送握手信息 ..."); myTCPServer.SendDataAsync(clientindex, serverHandshakeResponse, 0, serverHandshakeResponse.Length, HandshakeFinished, null); // ConnectionSocket.BeginSend(serverHandshakeResponse, 0, HandshakeText.Length + 16, 0, HandshakeFinished, null); //logger.Log(Handshake); } }
private void Read(TCPServer myTCPServer, uint clientIndex, int numberOfBytesReceived) { if (!myTCPServer.ClientConnected(clientindex)) { return; } string messageReceived = string.Empty; byte[] readBuffer = new byte[numberOfBytesReceived]; Array.Copy(myTCPServer.GetIncomingDataBufferForSpecificClient(clientindex), readBuffer, numberOfBytesReceived); DataFrame dr = new DataFrame(readBuffer); try { if (!this.isDataMasked) { // Web Socket protocol: messages are sent with 0x00 and 0xFF as padding bytes int startIndex = 0; int endIndex = 0; // Search for the start byte while (readBuffer[startIndex] == FirstByte[0]) { startIndex++; } // Search for the end byte endIndex = startIndex + 1; while (readBuffer[endIndex] != LastByte[0] && endIndex != MaxBufferSize - 1) { endIndex++; } if (endIndex == MaxBufferSize - 1) { endIndex = MaxBufferSize; } // Get the message messageReceived = Encoding.GetEncoding(28591).GetString(myTCPServer.GetIncomingDataBufferForSpecificClient(clientindex), startIndex, endIndex - startIndex); } else { messageReceived = dr.Text; } //if ((messageReceived.Length == MaxBufferSize && messageReceived[0] == Convert.ToChar(65533)) || // messageReceived.Length == 0) //{ // if (Disconnected != null) // Disconnected(this, EventArgs.Empty); //} //else { if (DataReceived != null) { DataReceived(this, messageReceived, EventArgs.Empty); } Array.Clear(readBuffer, 0, readBuffer.Length); myTCPServer.ReceiveDataAsync(clientindex, this.Read, 0); } } catch (Exception ex) { if (this.Log != null) { this.Log("ReadException:" + ex.Message); } if (Disconnected != null) { Disconnected(this, EventArgs.Empty); } } }