private void OnDataReceived(ConnectionEventArgs e) { if (DataReceived != null) { DataReceived(this, e); } }
private void OnHandshaked(ConnectionEventArgs e) { if (Handshaked != null) { Handshaked(this, e); } }
private void OnDisconnected(ConnectionEventArgs e) { if (Disconnected != null) { Disconnected(this, e); } }
private void OnConnected(ConnectionEventArgs e) { if (Connected != null) { Connected(this, e); } }
/// <summary> /// Decode request package /// </summary> /// <param name="e"></param> /// <param name="package"></param> /// <returns></returns> public bool TryDecodePackage(ConnectionEventArgs e, out RequestPackage package) { package = null; string paramStr = Encoding.ASCII.GetString(e.Data); int index = paramStr.IndexOf("?d=", StringComparison.CurrentCultureIgnoreCase); string routeName = string.Empty; if (index != -1) { if (paramStr.StartsWith("route:", StringComparison.CurrentCultureIgnoreCase)) { routeName = paramStr.Substring(6, index - 6); } paramStr = paramStr.Substring(index, paramStr.Length - index); paramStr = HttpUtility.ParseQueryString(paramStr)["d"]; } var nvc = HttpUtility.ParseQueryString(paramStr); var param = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); foreach (var key in nvc.AllKeys) { param[key] = nvc[key]; } if (param.ContainsKey("route")) { routeName = param["route"]; } //if (!param.ContainsKey("ssid")) { Interlocked.Increment(ref errorDropNum); return; } if (!param.ContainsKey("actionid")) { return false; } if (!param.ContainsKey("msgid")) { return false; } //sessionId of proxy server Guid proxySid; if (!param.ContainsKey("ssid") || !Guid.TryParse(param["ssid"], out proxySid)) { proxySid = Guid.Empty; } int actionid; if (!int.TryParse(param["actionid"], out actionid)) { return false; } int msgid; if (!int.TryParse(param["msgid"], out msgid)) { return false; } int userId; int.TryParse(param["uid"], out userId); string sessionId = param.ContainsKey("sid") ? param["sid"] : ""; package = new RequestPackage(msgid, sessionId, actionid, userId) { ProxySid = proxySid, IsProxyRequest = param.ContainsKey("isproxy"), RouteName = routeName, IsUrlParam = true, UrlParam = paramStr }; return true; }
protected override void OnConnectCompleted(object sender, ConnectionEventArgs e) { string address = e.Socket.RemoteEndPoint.ToString(); if (!_sessions.ContainsKey(address)) { var user = new GuestUser(); user.Init(); _sessions[address] = user; } }
public bool TryDecodePackage(ConnectionEventArgs e, out RequestPackage package) { //这里解出头部信息根据ActionId来分发请求到相应的Action子类 package = null; byte[] content; MessagePack head = ReadMessageHead(e.Data, out content); if (head == null) { return false; } package = new RequestPackage(head.MsgId, head.SessionId, head.ActionId, head.UserId) { Message = content }; return true; }
public bool TryDecodePackage(ConnectionEventArgs e, out RequestPackage package) { //这里解出头部信息根据ActionId来分发请求到相应的Action子类 package = null; byte[] content; //todo test 1001 action //MessagePack packageHead = new MessagePack { MsgId = 1, ActionId = 1001, SessionId = "", UserId = 1380001 }; //byte[] headBytes = ProtoBufUtils.Serialize(packageHead); //byte[] contentBytes = ProtoBufUtils.Serialize(new Request1001Pack() { PageIndex = 1, PageSize = 20 }); //e.Data = BufferUtils.MergeBytes(BufferUtils.AppendHeadBytes(headBytes), contentBytes); MessagePack head = ReadMessageHead(e.Data, out content); if (head == null) { return false; } package = new RequestPackage(head.MsgId, head.SessionId, head.ActionId, head.UserId) { Message = content }; return true; }
void socketLintener_Disconnected(object sender, ConnectionEventArgs e) { try { ClientConnection clientConnection; if (clientConnections.TryGetValue(e.Socket, out clientConnection)) { clientConnections.Remove(clientConnection.SSID); TraceLog.ReleaseWriteDebug("断开 IP:{0},ssid:{1}", clientConnection.Socket.RemoteEndPoint, clientConnection.SSID); if (clientConnection.ServerId != 0) { NameValueCollection requestParam = new NameValueCollection(); requestParam["actionid"] = ((int)ActionEnum.Interrupt).ToString(); requestParam["ssid"] = clientConnection.SSID.ToString("N"); requestParam["msgid"] = "0"; string paramStr = RequestParse.ToQueryString(requestParam); byte[] paramData = Encoding.ASCII.GetBytes(paramStr); try { gsConnectionManager.Send(clientConnection.GameId, clientConnection.ServerId, paramData); } catch (Exception ex) { TraceLog.WriteError("Send to tcp disconnected notify failed:{0}\r\nparam:{1}", ex, paramStr); } } } else { TraceLog.ReleaseWriteDebug("断开 IP:{0}。", e.Socket.RemoteEndPoint); } } catch (Exception err) { TraceLog.WriteError("Disconnected:{0}", err); } }
private void socketLintener_DataReceived(object sender, ConnectionEventArgs e) { try { Interlocked.Increment(ref receiveNum); OnReceivedBefore(e); RequestPackage package; if (!ActionDispatcher.TryDecodePackage(e, out package)) { return; } var session = GetSession(e, package); if (CheckSpecialPackge(package, session)) { return; } package.Session = session; package.ReceiveTime = DateTime.Now; requestQueue.Enqueue(package); singal.Set(); } catch (Exception ex) { TraceLog.WriteError("Received to Host:{0} error:{1}", e.Socket.RemoteEndPoint, ex); } }
private void socketLintener_Disconnected(object sender, ConnectionEventArgs e) { try { GameSession session = GameSession.Get(e.Socket.HashCode); if (session != null) { OnDisconnected(session); session.ProxySid = Guid.Empty; session.Close(); } } catch (Exception err) { TraceLog.WriteError("Disconnected error:{0}", err); } }
/// <summary> /// Raises the received before event. /// </summary> /// <param name="e">E.</param> protected virtual void OnReceivedBefore(ConnectionEventArgs e) { }
private GameSession GetSession(ConnectionEventArgs e, RequestPackage package) { //使用代理分发器时,每个ssid建立一个游服Serssion GameSession session; if (package.ProxySid != Guid.Empty) { session = GameSession.Get(package.ProxySid) ?? (package.IsProxyRequest ? GameSession.Get(e.Socket.HashCode) : GameSession.CreateNew(package.ProxySid, e.Socket, socketLintener.PostSend)); if (session != null) { session.ProxySid = package.ProxySid; } } else { session = GameSession.Get(package.SessionId) ?? GameSession.Get(e.Socket.HashCode); } if (session != null && !session.Connected) { GameSession.Recover(session, e.Socket.HashCode, e.Socket, socketLintener.PostSend); } return session; }
void socketLintener_DataReceived(object sender, ConnectionEventArgs e) { var data = Encoding.ASCII.GetString(e.Data); try { string routeName = string.Empty; int index = data.LastIndexOf("?d="); if (index > 0) { if (data.StartsWith("route:", StringComparison.CurrentCultureIgnoreCase)) { routeName = data.Substring(6, index - 6); } data = data.Substring(index, data.Length - index); } data = HttpUtility.ParseQueryString(data)["d"]; int gameId, serverId, statuscode; var ip = e.Socket.RemoteEndPoint.ToString().Split(new char[] { ':' })[0]; var requestParam = RequestParse.Parse(ip, "", data, out gameId, out serverId, out statuscode); if (statuscode != (int)HttpStatusCode.OK) {// 接收到非法数据 listener.CloseSocket(e.Socket); return; } ClientConnection clientConnection; if (!clientConnections.TryGetValue(e.Socket, out clientConnection)) { TraceLog.WriteError("接收到不在连接池中的socket数据,哪里有bug。"); listener.CloseSocket(e.Socket); return; } if (clientConnection.GameId == 0) clientConnection.GameId = gameId; if (clientConnection.ServerId == 0) clientConnection.ServerId = serverId; requestParam["UserHostAddress"] = ip; requestParam["ssid"] = clientConnection.SSID.ToString("N"); requestParam["http"] = "0"; string paramStr = string.Format("{0}&UserHostAddress={1}&ssid={2}&http=0", data, ip, requestParam["ssid"]); if (!string.IsNullOrEmpty(routeName)) { requestParam["route"] = routeName; paramStr += "&route=" + routeName; } byte[] paramData = Encoding.ASCII.GetBytes(paramStr); try { if (!gsConnectionManager.Send(gameId, serverId, paramData)) { var responseData = RequestParse.CtorErrMsg(10000, RequestParse.ErrorMsgConnectFail, requestParam); SendDataBack(clientConnection.SSID, responseData, 0, responseData.Length); } } catch (Exception ex) { TraceLog.WriteError("无法连接游服error:{0}\r\nparam:{1}", ex, paramStr); var responseData = RequestParse.CtorErrMsg(10000, RequestParse.ErrorMsgConnectFail, requestParam); SendDataBack(clientConnection.SSID, responseData, 0, responseData.Length); } } catch (Exception err) { TraceLog.WriteError("DataReceived error:{0},param:{1}", err, data); } }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void OnError(ISocket sender, ConnectionEventArgs e) { sender.CloseHandshake(e.Socket, "param error"); }
protected override void OnError(ISocket sender, ConnectionEventArgs e) { Console.WriteLine("Server send to {0} data error.", e.Socket.RemoteEndPoint); base.OnError(sender, e); }
protected override void OnReceivedBefore(ConnectionEventArgs e) { //Console.WriteLine("Url:{0}", Encoding.ASCII.GetString(e.Data)); }
/// <summary> /// Decode request package /// </summary> /// <param name="e"></param> /// <param name="package"></param> /// <returns></returns> public virtual bool TryDecodePackage(ConnectionEventArgs e, out RequestPackage package) { var packageReader = new PackageReader(e.Data, Encoding.UTF8); if (TryBuildPackage(packageReader, out package)) { package.OpCode = e.Meaage.OpCode; package.CommandMessage = e.Socket.IsWebSocket && e.Meaage.OpCode == OpCode.Text ? e.Meaage.Message : null; return true; } return false; }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void OnPong(ISocket sender, ConnectionEventArgs e) { }
private GameSession GetSession(ConnectionEventArgs e, RequestPackage package) { //使用代理分发器时,每个ssid建立一个游服Serssion GameSession session; if (package.ProxySid != Guid.Empty) { session = GameSession.Get(package.ProxySid) ?? (package.IsProxyRequest ? GameSession.Get(e.Socket.HashCode) : GameSession.CreateNew(package.ProxySid, e.Socket, socketListener)); if (session != null) { session.ProxySid = package.ProxySid; } } else { session = GameSession.Get(package.SessionId) ?? GameSession.Get(e.Socket.HashCode); } if (session == null) { session = GameSession.CreateNew(package.ProxySid, e.Socket, socketListener); } if ((!session.Connected || !Equals(session.RemoteAddress, e.Socket.RemoteEndPoint.ToString()))) { GameSession.Recover(session, e.Socket.HashCode, e.Socket, socketListener); } return session; }
private void socketLintener_DataReceived(object sender, ConnectionEventArgs e) { try { OnReceivedBefore(e); RequestPackage package; if (!ActionDispatcher.TryDecodePackage(e, out package)) { return; } var session = GetSession(e, package); if (CheckSpecialPackge(package, session)) { return; } package.Bind(session); ProcessPackage(package, session).Wait(); } catch (Exception ex) { TraceLog.WriteError("Received to Host:{0} error:{1}", e.Socket.RemoteEndPoint, ex); } }
private void socketLintener_OnConnectCompleted(object sender, ConnectionEventArgs e) { try { var session = GameSession.CreateNew(e.Socket.HashCode, e.Socket, socketListener); session.HeartbeatTimeoutHandle += OnHeartbeatTimeout; OnConnectCompleted(sender, e); } catch (Exception err) { TraceLog.WriteError("ConnectCompleted error:{0}", err); } }
private void socketLintener_OnConnectCompleted(object sender, ConnectionEventArgs e) { try { GameSession.CreateNew(e.Socket.HashCode, e.Socket, socketLintener.PostSend); OnConnectCompleted(sender, e); } catch (Exception err) { TraceLog.WriteError("ConnectCompleted error:{0}", err); } }
protected override void OnConnectCompleted(object sender, ConnectionEventArgs e) { Console.WriteLine("客户端IP:[{0}]已与服务器连接成功", e.Socket.RemoteEndPoint); base.OnConnectCompleted(sender, e); }
protected override void OnConnectCompleted(object sender, ConnectionEventArgs e) { }
protected override void OnConnectCompleted(object sender, ConnectionEventArgs e) { Console.WriteLine("Client:{0} connect to server.", e.Socket.RemoteEndPoint); }
void socketLintener_Connected(object sender, ConnectionEventArgs e) { try { var ssid = Guid.NewGuid(); var clientConnection = new ClientConnection { SSID = ssid, Socket = e.Socket }; TraceLog.ReleaseWriteDebug("连接 IP:{0},ssid:{1}", e.Socket.RemoteEndPoint, ssid); clientConnections.Add(ssid, e.Socket, clientConnection); } catch (Exception) { } }
/// <summary> /// Raises the connect completed event. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">E.</param> protected virtual void OnConnectCompleted(object sender, ConnectionEventArgs e) { }
protected override void OnHandshaked(ISocket sender, ConnectionEventArgs e) { Console.WriteLine("Client {0} connect to server.", e.Socket.RemoteEndPoint); base.OnHandshaked(sender, e); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void OnPing(ISocket sender, ConnectionEventArgs e) { sender.Pong(e.Socket); }