public override bool Handshake(IWebSocketSession session, WebSocketReceiveFilterBase previousFilter, out IReceiveFilter<IWebSocketFragment> dataFrameReader) { if (!VersionTag.Equals(session.SecWebSocketVersion) && NextProcessor != null) { return NextProcessor.Handshake(session, previousFilter, out dataFrameReader); } dataFrameReader = null; session.ProtocolProcessor = this; if (!session.AppServer.ValidateHandshake(session, session.Items.GetValue<string>(OriginKey, string.Empty))) return false; var secWebSocketKey = session.Items.GetValue<string>(WebSocketConstant.SecWebSocketKey, string.Empty); if (string.IsNullOrEmpty(secWebSocketKey)) { return false; } var responseBuilder = new StringBuilder(); string secKeyAccept = string.Empty; try { secKeyAccept = Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(secWebSocketKey + m_Magic))); } catch (Exception) { return false; } responseBuilder.AppendWithCrCf(WebSocketConstant.ResponseHeadLine10); responseBuilder.AppendWithCrCf(WebSocketConstant.ResponseUpgradeLine); responseBuilder.AppendWithCrCf(WebSocketConstant.ResponseConnectionLine); responseBuilder.AppendFormatWithCrCf(WebSocketConstant.ResponseAcceptLine, secKeyAccept); var subProtocol = session.GetAvailableSubProtocol(session.Items.GetValue<string>(WebSocketConstant.SecWebSocketProtocol, string.Empty)); if (!string.IsNullOrEmpty(subProtocol)) responseBuilder.AppendFormatWithCrCf(WebSocketConstant.ResponseProtocolLine, subProtocol); responseBuilder.AppendWithCrCf(); byte[] data = Encoding.UTF8.GetBytes(responseBuilder.ToString()); session.SendRawData(data, 0, data.Length); dataFrameReader = new WebSocketDataFrameReceiveFilter(); return true; }
protected override void Run(IWebSocketSession session, JObject message) { var login_req = message.ToObject <Login_Req>(); var py = GameMainEntry.Instance.PlayerModule.GetPlayer(login_req.Id); if (py == null) { py = GameMainEntry.Instance.PlayerModule.CreatePlayer(login_req.Id); } Log.Debug($"Py{py.Id}:登录成功"); py.CheckNetUser().Wait(); GameMainEntry.Instance.PlayerModule.SetSession_Py(py, session); py.SendAsync(Msg_Json.Create_Msg_Json(NetOpCode.Login_Res, new Login_Res { Res = 1 })); }
private void dgv_browsers_SelectionChanged(object sender, EventArgs e) { if (dgv_browsers.SelectedRows.Count > 0) { string tag = dgv_browsers.SelectedRows[0].Cells["EndPoint"].Value.ToString(); curr = server.WebSocketServices["/"].Sessions.Sessions.Where(x => { var Id = (string)x.Context.UserEndPoint.ToString(); return(Id == tag); }).FirstOrDefault(); } else { curr = null; } }
protected override void Run(IWebSocketSession session, JObject message) { var py = GameMainEntry.Instance.PlayerModule.Session_Pys.GetValueByKey(session.ID); if (py == null) { this.SendReLogin(session); return; } if (!GameMainEntry.Instance.SiloClientModule.INetUserEntry.IsConnected(py.Id).Result) { this.SendReLogin(session); return; } this.Run(py, message); }
void HandleSend(WebSocketDatagram p) { Debug.Assert(Sessions != null, "sessions not exist!"); IWebSocketSession session = null; if (Sessions.TryGetSession(p.ID, out session)) { if (session.ConnectionState == WebSocketState.Open) { Sessions.SendTo(p.Data, session.ID); } else { log.Info($"cannot send: id={p.ID} state={session.ConnectionState}"); } } }
public bool TryGetSession(string id, out IWebSocketSession session) { bool flag; string str = ((ServerState)this._state).CheckIfAvailable(false, true, false) ?? id.CheckIfValidSessionID(); if (str == null) { flag = this.tryGetSession(id, out session); } else { this._logger.Error(str); session = null; flag = false; } return(flag); }
public override bool Handshake(IWebSocketSession session, WebSocketReceiveFilterBase previousFilter, out IReceiveFilter<IWebSocketFragment> dataFrameReader) { var secKey1 = session.Items.GetValue<string>(WebSocketConstant.SecWebSocketKey1, string.Empty); var secKey2 = session.Items.GetValue<string>(WebSocketConstant.SecWebSocketKey2, string.Empty); dataFrameReader = null; if (string.IsNullOrEmpty(secKey1) && string.IsNullOrEmpty(secKey2) && NextProcessor != null) { return NextProcessor.Handshake(session, previousFilter, out dataFrameReader); } session.ProtocolProcessor = this; if (!session.AppServer.ValidateHandshake(session, session.Items.GetValue<string>(WebSocketConstant.Origin, string.Empty))) return false; var secKey3 = session.Items.GetValue<byte[]>(WebSocketConstant.SecWebSocketKey3, m_ZeroKeyBytes); var responseBuilder = new StringBuilder(); responseBuilder.AppendWithCrCf(WebSocketConstant.ResponseHeadLine00); responseBuilder.AppendWithCrCf(WebSocketConstant.ResponseUpgradeLine); responseBuilder.AppendWithCrCf(WebSocketConstant.ResponseConnectionLine); if (!string.IsNullOrEmpty(session.Origin)) responseBuilder.AppendFormatWithCrCf(WebSocketConstant.ResponseOriginLine, session.Origin); responseBuilder.AppendFormatWithCrCf(WebSocketConstant.ResponseLocationLine, session.UriScheme, session.Host, session.Path); var subProtocol = session.GetAvailableSubProtocol(session.Items.GetValue<string>(WebSocketConstant.SecWebSocketProtocol, string.Empty)); if (!string.IsNullOrEmpty(subProtocol)) responseBuilder.AppendFormatWithCrCf(WebSocketConstant.ResponseProtocolLine, subProtocol); responseBuilder.AppendWithCrCf(); byte[] data = Encoding.UTF8.GetBytes(responseBuilder.ToString()); session.SendRawData(data, 0, data.Length); //Encrypt message byte[] secret = GetResponseSecurityKey(secKey1, secKey2, secKey3); session.SendRawData(secret, 0, secret.Length); dataFrameReader = new WebSocketDataReceiveFilter(previousFilter); return true; }
protected override void Run(IWebSocketSession session, JObject message) { Task.Factory.StartNew(() => { var login_req = message.ToObject <WeChat_Login_Req>(); var str_requst = WeChatHelper.GetLogin(login_req.Code); Log.Debug("Requst:" + str_requst); var res = HttpHelper.CreateHttp(str_requst); var jsres = JObject.Parse(res); //jsres[""] //Log.Debug("res:"+res); WeChat_Login_Res weChat_Login_Res = new WeChat_Login_Res(); weChat_Login_Res.Id = jsres["openid"].Value <string>(); var bys = Msg_Json.Create_Msg_Json(NetOpCode.WeChat_Login_Res, weChat_Login_Res); session.Context.WebSocket.Send(bys); }); }
public override bool Handshake(IWebSocketSession session, WebSocketReceiveFilterBase previousFilter, out IReceiveFilter <IWebSocketFragment> dataFrameReader) { var secKey1 = session.Items.GetValue <string>(WebSocketConstant.SecWebSocketKey1, string.Empty); var secKey2 = session.Items.GetValue <string>(WebSocketConstant.SecWebSocketKey2, string.Empty); if (string.IsNullOrEmpty(secKey1) && string.IsNullOrEmpty(secKey2) && NextProcessor != null) { return(NextProcessor.Handshake(session, previousFilter, out dataFrameReader)); } session.ProtocolProcessor = this; var secKey3 = session.Items.GetValue <byte[]>(WebSocketConstant.SecWebSocketKey3, m_ZeroKeyBytes); var responseBuilder = new StringBuilder(); responseBuilder.AppendWithCrCf(WebSocketConstant.ResponseHeadLine00); responseBuilder.AppendWithCrCf(WebSocketConstant.ResponseUpgradeLine); responseBuilder.AppendWithCrCf(WebSocketConstant.ResponseConnectionLine); if (!string.IsNullOrEmpty(session.Origin)) { responseBuilder.AppendFormatWithCrCf(WebSocketConstant.ResponseOriginLine, session.Origin); } responseBuilder.AppendFormatWithCrCf(WebSocketConstant.ResponseLocationLine, session.UriScheme, session.Host, session.Path); var subProtocol = session.GetAvailableSubProtocol(session.Items.GetValue <string>(WebSocketConstant.SecWebSocketProtocol, string.Empty)); if (!string.IsNullOrEmpty(subProtocol)) { responseBuilder.AppendFormatWithCrCf(WebSocketConstant.ResponseProtocolLine, subProtocol); } responseBuilder.AppendWithCrCf(); byte[] data = Encoding.UTF8.GetBytes(responseBuilder.ToString()); session.SendRawData(data, 0, data.Length); //Encrypt message byte[] secret = GetResponseSecurityKey(secKey1, secKey2, secKey3); session.SendRawData(secret, 0, secret.Length); dataFrameReader = new WebSocketDataReceiveFilter(previousFilter); return(true); }
private void SendPackage(IWebSocketSession session, int opCode, byte[] data, int offset, int length) { byte[] fragment; if (length < 126) { fragment = new byte[2 + length]; fragment[1] = (byte)length; } else if (length < 65536) { fragment = new byte[4 + length]; fragment[1] = (byte)126; fragment[2] = (byte)(length / 256); fragment[3] = (byte)(length % 256); } else { fragment = new byte[10 + length]; fragment[1] = (byte)127; int left = length; int unit = 256; for (int i = 9; i > 1; i--) { fragment[i] = (byte)(left % unit); left = left / unit; if (left == 0) { break; } } } fragment[0] = (byte)(opCode | 0x80); if (length > 0) { Buffer.BlockCopy(data, offset, fragment, fragment.Length - length, length); } session.SendRawData(fragment, 0, fragment.Length); }
private bool tryGetSession(string id, out IWebSocketSession session) { session = null; if (_state != ServerState.Start) { return(false); } lock (_sync) { if (_state != ServerState.Start) { return(false); } return(_sessions.TryGetValue(id, out session)); } }
internal string Add(IWebSocketSession session) { string str; lock (this._sync) { if (this._state != 1) { str = null; } else { string key = createID(); this._sessions.Add(key, session); str = key; } } return(str); }
internal string Add(IWebSocketSession session) { object sync = this._sync; string result; lock (sync) { if (this._state != ServerState.Start) { result = null; } else { string text = WebSocketSessionManager.createID(); this._sessions.Add(text, session); result = text; } } return(result); }
public override void SendCloseHandshake(IWebSocketSession session, int statusCode, string closeReason) { byte[] playloadData = new byte[(string.IsNullOrEmpty(closeReason) ? 0 : Encoding.UTF8.GetMaxByteCount(closeReason.Length)) + 2]; int highByte = statusCode / 256; int lowByte = statusCode % 256; playloadData[0] = (byte)highByte; playloadData[1] = (byte)lowByte; var playloadLength = playloadData.Length; if (!string.IsNullOrEmpty(closeReason)) { int bytesCount = Encoding.UTF8.GetBytes(closeReason, 0, closeReason.Length, playloadData, 2); playloadLength = bytesCount + 2; } SendPackage(session, OpCode.Close, playloadData, 0, playloadLength); }
private bool tryGetSession(string id, out IWebSocketSession session) { bool flag; object obj = this._sync; Monitor.Enter(obj); try { flag = this._sessions.TryGetValue(id, out session); } finally { Monitor.Exit(obj); } if (!flag) { this._logger.Error(string.Concat("A session with the specified ID isn't found:\n ID: ", id)); } return(flag); }
async Task HandleWebSocketSession(IWebSocketSession session) { sessions[session.Id] = session; try { using (session) { BroadcastMessage(string.Format("*** session-{0} connected ({1} online)", session.Id, sessions.Count)); while (session.IsOpen) { var message = await session.ReadNextMessageAsync().ConfigureAwait(false); switch (message.MessageType) { case WebSocketMessage.Type.Text: var text = (WebSocketMessage.Text)message; BroadcastMessage(string.Format("<session-{0}> {1}", session.Id, text.Payload)); break; case WebSocketMessage.Type.Close: session.CloseSession(); break; case WebSocketMessage.Type.Ping: session.SendPong(); break; case WebSocketMessage.Type.Pong: break; } } } } finally { sessions.TryRemove(session.Id, out session); BroadcastMessage(string.Format("*** session-{0} disconnected", session.Id)); } }
async Task HandleWebSocketSession(IWebSocketSession session) { sessions[session.Id] = session; try { using (session) { BroadcastMessage(string.Format("*** session-{0} connected ({1} online)", session.Id, sessions.Count)); while (session.IsOpen) { var message = await session.ReadNextMessageAsync().ConfigureAwait(false); switch (message.MessageType) { case WebSocketMessage.Type.Text: var text = (WebSocketMessage.Text)message; BroadcastMessage(string.Format("<session-{0}> {1}", session.Id, text.Payload)); break; case WebSocketMessage.Type.Close: session.CloseSession(); break; case WebSocketMessage.Type.Ping: session.SendPong(); break; case WebSocketMessage.Type.Pong: break; } } } } finally { sessions.TryRemove(session.Id, out session); BroadcastMessage(string.Format("*** session-{0} disconnected", session.Id)); } }
/// <summary> /// Handshakes the specified protocol processor. /// </summary> /// <param name="protocolProcessor">The protocol processor.</param> /// <param name="session">The session.</param> /// <returns></returns> protected bool Handshake(IProtocolProcessor protocolProcessor, IWebSocketSession session) { IReceiveFilter <IWebSocketFragment> dataFrameReader; if (!protocolProcessor.Handshake(session, this, out dataFrameReader)) { session.Close(CloseReason.ServerClosing); return(false); } //Processor handshake sucessfully, but output datareader is null, so the multiple protocol switch handled the handshake //In this case, the handshake is not completed if (dataFrameReader == null) { NextReceiveFilter = this; return(false); } NextReceiveFilter = dataFrameReader; return(true); }
public virtual void Dispatch(IWebSocketSession session, MessageInfo_Json messageInfo) { List <IMWHandler> actions; if (!m_Dict_Handlers.TryGetValue(messageInfo.Opcode, out actions)) { Log.Error($"消息没有处理: {messageInfo.Opcode}"); return; } try { foreach (IMWHandler ev in actions) { ev.Handle(session, messageInfo.Message); } } catch (Exception e) { Log.Error(e); } }
protected virtual void SendReLogin(IWebSocketSession session) { var bys = Msg_Json.Create_Msg_Json <NeedLogin_Msg>(NetOpCode.NeedLogin_Msg, new NeedLogin_Msg()); session.Context.WebSocket.Send(bys); }
public override bool TrySendMessage(IWebSocketSession session, string message) { return(TrySendMessage(session, OpCode.Text, message)); }
public override void SendMessage(IWebSocketSession session, string message) { SendMessage(session, OpCode.Text, message); }
private void SendMessage(IWebSocketSession session, int opCode, string message) { byte[] playloadData = Encoding.UTF8.GetBytes(message); SendPackage(session, opCode, playloadData, 0, playloadData.Length); }
public override bool TrySendMessage(IWebSocketSession session, string message) { var packageData = GetPackageData(message); return session.TrySendRawData(packageData.Array, packageData.Offset, packageData.Count); }
public bool Handshake(IWebSocketSession session, WebSocketReceiveFilterBase previousReader, out IReceiveFilter <IWebSocketFragment> dataFrameReader) { dataFrameReader = null; session.SendRawData(m_SwitchResponse, 0, m_SwitchResponse.Length); return(true); }
public abstract void SendPing(IWebSocketSession session, byte[] ping);
public abstract void SendCloseHandshake(IWebSocketSession session, int statusCode, string closeReason);
public abstract void SendMessage(IWebSocketSession session, string message);
public abstract bool Handshake(IWebSocketSession session, WebSocketRequestFilterBase previousFilter, out IRequestFilter<IWebSocketFragment> dataFrameReader);
public abstract bool TrySendMessage(IWebSocketSession session, string message);
public override void SendMessage(IWebSocketSession session, string message) { var packageData = GetPackageData(message); session.SendRawData(packageData.Array, packageData.Offset, packageData.Count); }
public override void SendCloseHandshake(IWebSocketSession session, int statusCode, string closeReason) { session.SendRawData(WebSocketConstant.ClosingHandshake, 0, WebSocketConstant.ClosingHandshake.Length); }
public override void SendData(IWebSocketSession session, byte[] data, int offset, int length) { throw new NotSupportedException(); }
public abstract void SendData(IWebSocketSession session, byte[] data, int offset, int length);
public void SendPing(IWebSocketSession session, byte[] ping) { throw new NotImplementedException(); }
public void SendPong(IWebSocketSession session, byte[] pong) { throw new NotImplementedException(); }
private void SendPackage(IWebSocketSession session, int opCode, byte[] data, int offset, int length) { byte[] fragment; if (length < 126) { fragment = new byte[2 + length]; fragment[1] = (byte)length; } else if (length < 65536) { fragment = new byte[4 + length]; fragment[1] = (byte)126; fragment[2] = (byte)(length / 256); fragment[3] = (byte)(length % 256); } else { fragment = new byte[10 + length]; fragment[1] = (byte)127; int left = length; int unit = 256; for (int i = 9; i > 1; i--) { fragment[i] = (byte)(left % unit); left = left / unit; if (left == 0) break; } } fragment[0] = (byte)(opCode | 0x80); if (length > 0) { Buffer.BlockCopy(data, offset, fragment, fragment.Length - length, length); session.EnqueueSend(new ArraySegment<byte>(fragment, 0, fragment.Length)); } else { session.EnqueueSend(new ArraySegment<byte>(fragment, 0, fragment.Length)); } }
public void SendMessage(IWebSocketSession session, string message) { throw new NotImplementedException(); }
public override void SendData(IWebSocketSession session, byte[] data, int offset, int length) { SendPackage(session, OpCode.Binary, data, offset, length); }
public bool TrySendData(IWebSocketSession session, byte[] data, int offset, int length) { throw new NotImplementedException(); }
public override void SendCloseHandshake(IWebSocketSession session, int statusCode, string closeReason) { byte[] playloadData = new byte[(string.IsNullOrEmpty(closeReason) ? 0 : Encoding.UTF8.GetMaxByteCount(closeReason.Length)) + 2]; int highByte = statusCode / 256; int lowByte = statusCode % 256; playloadData[0] = (byte)highByte; playloadData[1] = (byte)lowByte; if (!string.IsNullOrEmpty(closeReason)) { int bytesCount = Encoding.UTF8.GetBytes(closeReason, 0, closeReason.Length, playloadData, 2); SendPackage(session, OpCode.Close, playloadData, 0, bytesCount + 2); } else { SendPackage(session, OpCode.Close, playloadData, 0, playloadData.Length); } }
internal string Add(IWebSocketSession session) { lock (_sync) { if (_state != ServerState.Start) return null; var id = createID (); _sessions.Add (id, session); return id; } }
private bool TrySendMessage(IWebSocketSession session, int opCode, string message) { byte[] playloadData = Encoding.UTF8.GetBytes(message); return(TrySendPackage(session, opCode, playloadData, 0, playloadData.Length)); }
public void SendCloseHandshake(IWebSocketSession session, int statusCode, string closeReason) { throw new NotImplementedException(); }
public override bool TrySendData(IWebSocketSession session, byte[] data, int offset, int length) { return(TrySendPackage(session, OpCode.Binary, data, offset, length)); }
public override void SendPing(IWebSocketSession session, byte[] ping) { }
public override void SendMessage(IWebSocketSession session, string message) { var packageData = GetPackageData(message); session.SendRawData(packageData.Array, packageData.Offset, packageData.Count); }
public override void SendData(IWebSocketSession session, byte[] data, int offset, int length) { throw new NotSupportedException(); }
public override void SendPing(IWebSocketSession session, byte[] ping) { }
public bool Handshake(IWebSocketSession session, WebSocketReceiveFilterBase previousReader, out IReceiveFilter<IWebSocketFragment> dataFrameReader) { dataFrameReader = null; session.SendRawData(m_SwitchResponse, 0, m_SwitchResponse.Length); return true; }
public override bool TrySendMessage(IWebSocketSession session, string message) { var packageData = GetPackageData(message); return(session.TrySendRawData(packageData.Array, packageData.Offset, packageData.Count)); }
private bool tryGetSession (string id, out IWebSocketSession session) { bool result; lock (_sync) { result = _sessions.TryGetValue (id, out session); } if (!result) _logger.Error ("A WebSocket session with the specified ID not found.\nID: " + id); return result; }
public void SendCloseHandshake(IWebSocketSession session, int statusCode, string closeReason) { throw new NotImplementedException(); }
public override void SendPing(IWebSocketSession session, byte[] ping) { SendPackage(session, OpCode.Ping, ping, 0, ping.Length); }
public bool TrySendMessage(IWebSocketSession session, string message) { throw new NotImplementedException(); }
public override bool TrySendData(IWebSocketSession session, byte[] data, int offset, int length) { throw new NotImplementedException(); }
/// <summary> /// Tries to get the session with the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the session is successfully found; otherwise, <c>false</c>. /// </returns> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="session"> /// When this method returns, a <see cref="IWebSocketSession"/> instance that /// provides the access to the information in the session, or <see langword="null"/> /// if it's not found. This parameter is passed uninitialized. /// </param> public bool TryGetSession(string id, out IWebSocketSession session) { var msg = _state.CheckIfAvailable (false, true, false) ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); session = null; return false; } return tryGetSession (id, out session); }
public override void SendMessage(IWebSocketSession session, string message) { var maxByteCount = Encoding.UTF8.GetMaxByteCount(message.Length) + 2; var sendBuffer = new byte[maxByteCount]; sendBuffer[0] = WebSocketConstant.StartByte; int bytesCount = Encoding.UTF8.GetBytes(message, 0, message.Length, sendBuffer, 1); sendBuffer[1 + bytesCount] = WebSocketConstant.EndByte; session.SocketSession.SendResponse(sendBuffer, 0, bytesCount + 2); }
private bool tryGetSession(string id, out IWebSocketSession session) { bool ret; lock (_sync) ret = _sessions.TryGetValue (id, out session); if (!ret) _logger.Error ("A session with the specified ID isn't found:\n ID: " + id); return ret; }
public override void SendCloseHandshake(IWebSocketSession session, int statusCode, string closeReason) { session.SocketSession.SendResponse(WebSocketConstant.ClosingHandshake, 0, WebSocketConstant.ClosingHandshake.Length); }