private void ReadMessageAync(IAsyncResult ar) { var sock = (Socket)ar.AsyncState; try { var countread = sock.EndReceive(ar); if (countread > 0) { var data = _Encoding.GetString(_readbuffer); if (new System.Text.RegularExpressions.Regex("websocket").IsMatch(data) && !_SocketHandshake) { WebSocketSecKey = new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)") .Match(data).Groups[1].Value.Trim(); const string eol = "\r\n"; // HTTP/1.1 defines the sequence CR LF as the end-of-line marker Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol + "Connection: Upgrade" + eol + "Upgrade: websocket" + eol + "Sec-WebSocket-Accept: " + Convert.ToBase64String(System.Security.Cryptography.SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes( WebSocketSecKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"))) + eol + eol); _ClientSocket.Send(response); _SocketHandshake = true; _Sockettype = MySocketType.Websocket; } else { var message = MessageHandle.PrepareReceivedData(_readbuffer, _Encoding); if (!string.IsNullOrWhiteSpace(message.Text) && !string.IsNullOrWhiteSpace(message.FromId) && !string.IsNullOrWhiteSpace(message.ToId)) { ClientId = string.IsNullOrWhiteSpace(ClientId) ? message.FromId : ClientId; SendingMessageQueue.SendingMessages.Enqueue(message); } } } } catch (Exception e) { Console.WriteLine("Error In SendMessage Method : " + e.Message); } // sock.EndConnect(ar); WaitforData(); }
public static byte[] PrepareDataforSending(MessageUM msg, Encoding encoding, MySocketType sockettype, string webSocketSecKey) { try { if (sockettype != MySocketType.Websocket) { return(encoding.GetBytes(msg.Text)); } var lb = new List <byte> { 0x81, (byte)msg.Text.Length }; lb.AddRange(Encoding.UTF8.GetBytes(msg.Text)); return(lb.ToArray()); } catch (Exception e) { Console.WriteLine("Error In PreaparingData Method : " + e.Message); return(null); } }
/* public MySocket(MySocketType type) { MySocket(type,BUFFER_SIZE,0); } public MySocket(MySocketType type, int bufferSize) { MySocket(type,bufferSize,0); } */ public MySocket(MySocketType type, int bufferSize, int port) { epRemote = (System.Net.EndPoint) new System.Net.IPEndPoint(System.Net.IPAddress.Any,0); epLocal = (System.Net.EndPoint) new System.Net.IPEndPoint(Dns.Resolve(Environment.MachineName).AddressList[0],port); switch (type) { case MySocketType.TcpSocket: socketLocal = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); break; case MySocketType.UdpSocket: socketLocal = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); break; } socketLocal.Bind(epLocal); this.buffer = new byte[bufferSize]; }