public override void TakeActionAffter(bool state) { //ms.WriteByte(_message); MessageStructure ms = new MessageStructure(); //ms.PushIntoStack(); ms.PushIntoStack(true); ms.WriteBuffer(new MessageHead(2010)); byte[] buffer = ms.PopBuffer(); //Current.SendAsync(buffer, 0, buffer.Length); var list = GameSession.GetOnlineAll(10 * 1000); list.ForEach(r => { if (r.SessionId != Current.SessionId) { r.SendAsync(OpCode.Text, buffer, 0, buffer.Length, asyncResult => { Console.WriteLine("The results of data send:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail"); }); } }); base.TakeActionAffter(state); }
/// <summary> /// 出错处理 /// </summary> /// <param name="response"></param> /// <param name="actionID"></param> /// <param name="errorCode"></param> /// <param name="errorInfo"></param> public static void RequestError(IGameResponse response, int actionID, int errorCode, string errorInfo) { MessageHead head = new MessageHead(actionID, errorCode, errorInfo); MessageStructure sb = new MessageStructure(); sb.WriteBuffer(head); response.BinaryWrite(sb.PopBuffer()); }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <param name="actionGetter"></param> /// <param name="errorCode"></param> /// <param name="errorInfo"></param> public virtual void ResponseError(BaseGameResponse response, ActionGetter actionGetter, int errorCode, string errorInfo) { MessageHead head = new MessageHead(actionGetter.GetMsgId(), actionGetter.GetActionId(), errorCode, errorInfo); MessageStructure sb = new MessageStructure(); sb.WriteBuffer(head); response.BinaryWrite(sb.PopBuffer()); }
public void ProcessPackage(RequestPackage package, GameSession session) { if (package == null) { return; } try { var watch = RunTimeWatch.StartNew(string.Format("当前线程{0},{1}协议执行时间", Thread.CurrentThread.ManagedThreadId, package.ActionId)); ActionGetter actionGetter; byte[] data = new byte[0]; if (!string.IsNullOrEmpty(package.RouteName)) { actionGetter = ActionDispatcher.GetActionGetter(package, session); if (CheckRemote(package.RouteName, actionGetter)) { MessageStructure response = new MessageStructure(); OnCallRemote(package.RouteName, actionGetter, response); data = response.PopBuffer(); } else { return; } } else { SocketGameResponse response = new SocketGameResponse(); response.WriteErrorCallback += ActionDispatcher.ResponseError; actionGetter = ActionDispatcher.GetActionGetter(package, session); DoAction(actionGetter, response); data = response.ReadByte(); } try { if (session != null && data.Length > 0) { session.SendAsync(actionGetter.OpCode, data, 0, data.Length, OnSendCompleted); } } catch (Exception ex) { TraceLog.WriteError("PostSend error:{0}", ex); } watch.Flush(true); } catch (Exception ex) { TraceLog.WriteError("Task error:{0}", ex); } finally { if (session != null) { session.ExitSession(); } } }
public void ActiveHttp(NewHttpResponse client, Dictionary <string, string> parms) { MessageStructure receipt = verifyDeliver(parms); //string buffer = Encoding.UTF8.GetString(); string buffer = Convert.ToBase64String(receipt.PopBuffer()); client.OutputStream.WriteLine(buffer); client.Close(); }
/// <summary> /// 还未连接上路由服情况处理 /// </summary> public async System.Threading.Tasks.Task ProcessNotReady(RequestPackage package, GameSession session) { if (package == null) { return; } try { ActionGetter actionGetter; byte[] data = new byte[0]; if (!string.IsNullOrEmpty(package.RouteName)) { actionGetter = ActionDispatcher.GetActionGetter(package, session); if (CheckRemote(package.RouteName, actionGetter)) { MessageStructure response = new MessageStructure(); OnCallRemote(package.RouteName, actionGetter, response); data = response.PopBuffer(); } else { return; } } else { SocketGameResponse response = new SocketGameResponse(); response.WriteErrorCallback += ActionDispatcher.ResponseError; actionGetter = ActionDispatcher.GetActionGetter(package, session); response.WriteError(actionGetter, Language.Instance.ErrorCode, Language.Instance.ServerBusy); data = response.ReadByte(); } try { if (session != null && data.Length > 0) { await session.SendAsync(actionGetter.OpCode, data, 0, data.Length, OnSendCompleted); } } catch (Exception ex) { TraceLog.WriteError("PostSend error:{0}", ex); } } catch (Exception ex) { TraceLog.WriteError("Task error:{0}", ex); } finally { if (session != null) { session.ExitSession(); } } }
private void ProcessPackage(RequestPackage package, GameSession session) { if (package == null) { return; } try { ActionGetter actionGetter; byte[] data = new byte[0]; if (!string.IsNullOrEmpty(package.RouteName)) { actionGetter = ActionDispatcher.GetActionGetter(package, session); if (CheckRemote(package.RouteName, actionGetter)) { MessageStructure response = new MessageStructure(); OnCallRemote(package.RouteName, actionGetter, response); data = response.PopBuffer(); } else { return; } } else { SocketGameResponse response = new SocketGameResponse(); response.WriteErrorCallback += ActionDispatcher.ResponseError; actionGetter = ActionDispatcher.GetActionGetter(package, session); DoAction(actionGetter, response); data = response.ReadByte(); } try { if (session != null && data.Length > 0) { session.SendAsync(actionGetter.OpCode, data, 0, data.Length); } } catch (Exception ex) { TraceLog.WriteError("PostSend error:{0}", ex); } } catch (Exception ex) { TraceLog.WriteError("Task error:{0}", ex); } finally { if (session != null) { session.ExitSession(); } } }
private void ProcessPackage(object state) { var package = (RequestPackage)state; if (package == null) { return; } var session = package.Session; try { byte[] data = new byte[0]; if (!string.IsNullOrEmpty(package.RouteName)) { HttpGet httpGet = new HttpGet(package); if (CheckRemote(package.RouteName, httpGet)) { MessageStructure response = new MessageStructure(); OnCallRemote(package.RouteName, httpGet, response); data = response.PopBuffer(); } } else { SocketGameResponse response = new SocketGameResponse(); response.WriteErrorCallback += ActionDispatcher.ResponseError; ActionGetter actionGetter = ActionDispatcher.GetActionGetter(package); OnRequested(actionGetter, response); data = response.ReadByte(); } try { if (data.Length > 0) { session.SendAsync(data, 0, data.Length); } } catch (Exception ex) { TraceLog.WriteError("PostSend异常{0}", ex); } } catch (Exception ex) { TraceLog.WriteError("Task异常{0}", ex); } finally { session.ExitSession(); Interlocked.Decrement(ref runningNum); } }
public IByteBuffer TryEncodePackage(ResponsePackage package, byte[] data = null) { MessageHead head = new MessageHead(package.MsgId, package.ActionId, package.St, package.ErrorCode, package.ErrorInfo); MessageStructure sb = new MessageStructure(); sb.WriteBuffer(head); if (data != null && data.Length != 0) { sb.WriteByte(data); } return(Unpooled.WrappedBuffer(sb.PopBuffer())); }
public override void TakeActionAffter(bool state) { //ms.WriteByte(_message); var cUser = (GameUser)Current.User; MessageStructure ms = new MessageStructure(); //ms.PushIntoStack(); ms.PushIntoStack(true); ms.WriteBuffer(new MessageHead(2010)); byte[] buffer = ms.PopBuffer(); //Current.SendAsync(buffer, 0, buffer.Length); var rUser = GameSession.GetOnlineAll(10 * 1000).FirstOrDefault(r => r.UserId == cUser.RivalId); //list.ForEach(r => //{ // if (r.SessionId != Current.SessionId) // r.SendAsync(OpCode.Text, buffer, 0, buffer.Length, asyncResult => // { // Console.WriteLine("The results of data send:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail"); // }); //}); if (rUser != null) { rUser.SendAsync(OpCode.Text, buffer, 0, buffer.Length, asyncResult => { Console.WriteLine("The results of data send:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail"); }); } if (cUser != null) { cUser.ModifyLocked(() => { cUser.RoomId = string.Empty; cUser.Searching = false; cUser.RivalId = -1; }); } base.TakeActionAffter(state); }
/// <summary> /// /// </summary> /// <param name="response"></param> /// <param name="actionGetter"></param> /// <param name="errorCode"></param> /// <param name="errorInfo"></param> public virtual void ResponseError(BaseGameResponse response, ActionGetter actionGetter, int errorCode, string errorInfo) { string st = actionGetter.GetSt(); ProtocolVersion prtcl = actionGetter.GetPtcl(); MessageHead head = new MessageHead(actionGetter.GetMsgId(), actionGetter.GetActionId(), st, errorCode, errorInfo); MessageStructure sb = new MessageStructure(); if (prtcl >= ProtocolVersion.ExtendHead) { sb.PushIntoStack(0); //不输出扩展头属性 } sb.WriteBuffer(head); response.BinaryWrite(sb.PopBuffer()); }
/// <summary> /// Response hearbeat stream. /// </summary> /// <param name="package"></param> /// <param name="session"></param> protected void ResponseHearbeat(RequestPackage package, GameSession session) { try { MessageStructure response = new MessageStructure(); response.WriteBuffer(new MessageHead(package.MsgId, package.ActionId, 0)); var data = response.PopBuffer(); if (session != null && data.Length > 0) { session.SendAsync(OpCode.Binary, data, 0, data.Length, OnSendCompleted).Wait(); } } catch (Exception ex) { TraceLog.WriteError("Post Heartbeat error:{0}", ex); } }
protected override void OnDisconnected(GameSession session) { Console.WriteLine("客户端UserId:[{0}]已与服务器断开", session.UserId); var cUser = (GameUser)session.User; if (cUser != null) { MessageStructure ms = new MessageStructure(); //ms.PushIntoStack(); ms.PushIntoStack(true); ms.WriteBuffer(new MessageHead(2010)); byte[] buffer = ms.PopBuffer(); //Current.SendAsync(buffer, 0, buffer.Length); Console.WriteLine("客户端RivalId:[{0}]将会收到离开消息", cUser.RivalId); var rUser = GameSession.GetOnlineAll(10 * 1000).Find(r => r.UserId == cUser.RivalId); if (rUser != null) { rUser.SendAsync(OpCode.Text, buffer, 0, buffer.Length, asyncResult => { Console.WriteLine("The results of data send:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail"); }); } else { Console.WriteLine("客户端RivalUser为空"); } } else { Console.WriteLine("客户端GameUser为空"); } base.OnDisconnected(session); }
private static byte[] DoSerialize(params BaseEntity[] entityList) { var rootWriter = new MessageStructure(); rootWriter.PushIntoStack(entityList.Length); object fieldValue = null; foreach (var entity in entityList) { var schema = entity.GetSchema(); if (schema == null) { continue; } var recordWriter = new MessageStructure(); recordWriter.PushIntoStack(schema.EntityName); //write columns var columns = schema.GetColumns(); foreach (var column in columns) { fieldValue = entity.GetPropertyValue(column.Name); if (EntitySchemaSet.IsSupportType(column.ColumnType)) { recordWriter.PushIntoStack(column.ColumnType, fieldValue); } else if (column.HasChild) { PushChildStack(recordWriter, column, fieldValue); } } rootWriter.PushIntoStack(recordWriter); } var head = new MessageHead(SyncActionId); rootWriter.WriteBuffer(head); return(rootWriter.PopBuffer()); }
/// <summary> /// /// </summary> /// <param name="package"></param> /// <param name="param"></param> /// <returns></returns> public byte[] ProcessRequest(object package, object param) { var httpresponse = new SocketGameResponse(); ActionGetter actionGetter = null; try { httpresponse.WriteErrorCallback += TNet.Runtime.GameZone.Setting.ActionDispatcher.ResponseError; RequestPackage p = package as RequestPackage; actionGetter = param as ActionGetter; if (!string.IsNullOrEmpty(p.RouteName)) { if (CheckRemote(p.RouteName, actionGetter)) { MessageStructure response = new MessageStructure(); OnCallRemote(p.RouteName, actionGetter, response); return(response.PopBuffer()); } httpresponse.WriteError(actionGetter, 10000, "No permission"); } else { DoAction(actionGetter, httpresponse); } return(httpresponse.ReadByte()); } catch (Exception ex) { TraceLog.WriteError("Request error:{0}", ex); MessageStructure response = new MessageStructure(); response.WriteBuffer(new MessageHead(0, 10000, "request error")); return(response.PopBuffer()); } }
private void ProcessPackage(object state) { var package = (RequestPackage)state; if (package == null) { return; } var param = package.Param; var session = package.Session; var actionid = package.ActionId; try { if (actionid == (int)ActionEnum.Heartbeat) { // 客户端tcp心跳包 session.LastActivityTime = DateTime.Now; OnHeartbeat(session); session.ExitSession(); Interlocked.Decrement(ref runningNum); return; } HttpGet httpGet = new HttpGet(param, session); byte[] data = new byte[0]; if (!string.IsNullOrEmpty(package.Route)) { if (CheckRemote(package.Route, httpGet)) { MessageStructure response = new MessageStructure(); OnCallRemote(package.Route, httpGet, response); data = response.PopBuffer(); } } else { SocketGameResponse response = new SocketGameResponse(); OnRequested(httpGet, response); data = response.ReadByte(); } try { session.SendAsync(data, 0, data.Length); } catch (Exception ex) { TraceLog.WriteError("PostSend异常{0}", ex); } } catch (Exception ex) { TraceLog.WriteError("Task异常{0}", ex); } finally { session.ExitSession(); Interlocked.Decrement(ref runningNum); } }
public override void TakeActionAffter(bool state) { GameSession gameSession = null; GameSession.GetOnlineAll(10 * 1000).ForEach(r => { var user = (GameUser)r.User; if (r.UserId != Current.UserId && user.Searching) { gameSession = r; return; } }); if (gameSession != null) { MessageStructure ms = new MessageStructure(); //ms.PushIntoStack(); ms.PushIntoStack(true); ms.WriteBuffer(new MessageHead(2009)); byte[] buffer = ms.PopBuffer(); Current.SendAsync(OpCode.Text, buffer, 0, buffer.Length, asyncResult => { Console.WriteLine("The results of data send:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail"); }); gameSession.SendAsync(OpCode.Text, buffer, 0, buffer.Length, asyncResult => { Console.WriteLine("The results of data send:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail"); }); var cUser = (GameUser)Current.User; var vUser = (GameUser)gameSession.User; cUser.ModifyLocked(() => { cUser.Searching = false; cUser.RivalId = vUser.UserId; }); vUser.ModifyLocked(() => { vUser.Searching = false; vUser.RivalId = cUser.UserId; }); } //ms.WriteByte(_message); //var cache = new PersonalCacheStruct<GameUser>(); //var persons= cache.FindGlobal(r=>r.Searching==true);//.Where(r => r.Searching == true); //bool start = false; //if (persons.Count()>1) //{ // start = true; //} //MessageStructure ms = new MessageStructure(); ////ms.PushIntoStack(); //ms.PushIntoStack(start); //ms.WriteBuffer(new MessageHead(2009)); //byte[] buffer = ms.PopBuffer(); ////Current.SendAsync(buffer, 0, buffer.Length); //var list = GameSession.GetOnlineAll(10 * 1000); //if (start) //{ // list.ForEach(r => // { // //if (r.SessionId != Current.SessionId) // r.SendAsync(OpCode.Text, buffer, 0, buffer.Length, asyncResult => // { // Console.WriteLine("The results of data send:{0}", asyncResult.Result == ResultCode.Success ? "ok" : "fail"); // }); // }); // foreach (var p in persons) // { // p.ModifyLocked(() => // { // //_user.RoomId = Guid.NewGuid().ToString(); // _user.Searching = false; // }); // } //} base.TakeActionAffter(state); }
private void OnHttpRequest(IAsyncResult result) { try { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); listener.BeginGetContext(OnHttpRequest, listener); RequestPackage package; if (!ActionDispatcher.TryDecodePackage(context, out package)) { return; } GameSession session; if (package.ProxySid != Guid.Empty) { session = GameSession.Get(package.ProxySid) ?? GameSession.CreateNew(package.ProxySid, context.Request); session.ProxySid = package.ProxySid; } else { session = GameSession.Get(package.SessionId) ?? GameSession.CreateNew(Guid.NewGuid(), context.Request); } package.Bind(session); ActionGetter httpGet = ActionDispatcher.GetActionGetter(package); if (package.IsUrlParam) { httpGet["UserHostAddress"] = session.EndAddress; httpGet["ssid"] = session.KeyCode.ToString("N"); httpGet["http"] = "1"; } var httpresponse = new SocketGameResponse(); httpresponse.WriteErrorCallback += new ScutActionDispatcher().ResponseError; var clientConnection = new HttpClientConnection { Context = context, Session = session, ActionGetter = httpGet, GameResponse = httpresponse }; clientConnection.TimeoutTimer = new Timer(OnHttpRequestTimeout, clientConnection, httpRequestTimeout, Timeout.Infinite); byte[] respData = new byte[0]; if (!string.IsNullOrEmpty(package.RouteName)) { if (CheckRemote(package.RouteName, httpGet)) { MessageStructure response = new MessageStructure(); OnCallRemote(package.RouteName, httpGet, response); respData = response.PopBuffer(); } } else { DoAction(httpGet, httpresponse); respData = httpresponse.ReadByte(); } OnHttpResponse(clientConnection, respData, 0, respData.Length); } catch (Exception ex) { TraceLog.WriteError("OnHttpRequest error:{0}", ex); } }
private async System.Threading.Tasks.Task ProcessPackage(RequestPackage package, GameSession session) { if (package == null) { return; } try { ActionGetter actionGetter; byte[] data = new byte[0]; if (!string.IsNullOrEmpty(package.RouteName)) { actionGetter = ActionDispatcher.GetActionGetter(package, session); if (CheckRemote(package.RouteName, actionGetter)) { MessageStructure response = new MessageStructure(); OnCallRemote(package.RouteName, actionGetter, response); data = response.PopBuffer(); } else { return; } } else { SocketGameResponse response = new SocketGameResponse(); response.WriteErrorCallback += ActionDispatcher.ResponseError; actionGetter = ActionDispatcher.GetActionGetter(package, session); DoAction(actionGetter, response); data = response.ReadByte(); } try { if (session != null && data.Length > 0) { byte userRet = 0; string userSid = string.Empty; if (actionGetter.GetByte("UserRet", ref userRet) && userRet == (byte)1 && actionGetter.GetString("UserSid", ref userSid)) { var switchSession = ServerSsMgr.GetSwitchSession(); //未连接上路由服,则发给大厅服,由大厅服转发 if (switchSession == null) { var paramStr = "ActionId=100&MsgId=0&UserSid=" + userSid; string sign = SignUtils.EncodeSign(paramStr, RequestParam.SignKey); paramStr += string.Format("&{0}={1}", "sign", sign); var postData = Encoding.UTF8.GetBytes(string.Format("?d={0}", paramStr)); byte[] paramBytes = new byte[postData.Length + PackageReader.EnterChar.Length + data.Length]; Buffer.BlockCopy(postData, 0, paramBytes, 0, postData.Length); Buffer.BlockCopy(PackageReader.EnterChar, 0, paramBytes, postData.Length, PackageReader.EnterChar.Length); Buffer.BlockCopy(data, 0, paramBytes, postData.Length + PackageReader.EnterChar.Length, data.Length); await session.SendAsync(actionGetter.OpCode, paramBytes, 0, paramBytes.Length, OnSendCompleted); } //已连接上路由服,则直接发给路由服 else { var paramStr = "ActionId=101&MsgId=0&UserSid=" + userSid; string sign = SignUtils.EncodeSign(paramStr, RequestParam.SignKey); paramStr += string.Format("&{0}={1}", "sign", sign); var postData = Encoding.UTF8.GetBytes(string.Format("?d={0}", paramStr)); byte[] paramBytes = new byte[postData.Length + PackageReader.EnterChar.Length + data.Length]; Buffer.BlockCopy(postData, 0, paramBytes, 0, postData.Length); Buffer.BlockCopy(PackageReader.EnterChar, 0, paramBytes, postData.Length, PackageReader.EnterChar.Length); Buffer.BlockCopy(data, 0, paramBytes, postData.Length + PackageReader.EnterChar.Length, data.Length); await switchSession.SendAsync(actionGetter.OpCode, paramBytes, 0, paramBytes.Length, OnSendCompleted); } } } } catch (Exception ex) { TraceLog.WriteError("PostSend error:{0}", ex); } } catch (Exception ex) { TraceLog.WriteError("Task error:{0}", ex); } finally { if (session != null) { session.ExitSession(); } } }