void OnMyReceived(Connection connection, byte[] buffer, int offset, int size) { Message msg = clientCore.Serializer.Deserialize(buffer, offset, size); if (msg.Id != (int)EGMI.EGMI_LOGIN_RES) { LogU.Error("Unhandled message:{0}", msg.Id); return; } if (clientCore == null || clientCore.onLogin == null) { return; } LoginRes response = (LoginRes)msg.GetPb(typeof(LoginRes)); if (response == null) { clientCore.onLogin((int)EGEC.EGEC_CORE_DESERIALIZE_ERROR, 1, "", -1, null); } else { if (response.result == (int)EGEC.EGEC_CORE_SUCCESS) { clientCore.Token = guid + response.token; clientCore.AccountId = response.accountId; } clientCore.onLogin(response.result, response.accountId, response.token, response.lastAreaId, response.areas); } connection.Disconnect(true); }
void OnMyReceived(Connection connection, byte[] buffer, int offset, int size) { Message msg = clientCore.Serializer.Deserialize(buffer, offset, size); if (msg.Id != (int)EGMI.EGMI_CREATE_ACCOUNT_RES) { LogU.Error("Unhandled message:{0}", msg.Id); return; } if (clientCore == null || clientCore.onCreate == null) { return; } CreateAccountRes response = (CreateAccountRes)msg.GetPb(typeof(CreateAccountRes)); if (response == null) { clientCore.onCreate((int)EGEC.EGEC_CORE_DESERIALIZE_ERROR); } else { clientCore.onCreate(response.result); } connection.Disconnect(true); }
protected int msgCount; //数据部分实际长度 public void OnReceived(Connection connection, byte[] buffer, int offset, int count) { if (networkBuffer == null) { networkBuffer = new NetworkBuffer(NHNet._MAX_COMPRESS_MESSAGE_SIZE, true); } networkBuffer.Write(buffer, offset, count); try { CallDecode(connection); } catch (Exception e) { LogU.Debug(e.Message); LogU.Debug(e.StackTrace); //通知connection,连接异常 if (null != connection.OnReceived) { connection.OnReceived(connection, null, 0, -1); } } }
public static void OnReceive(int result, nicehu.clientcore.Player player) { if (result == (int)EGEC.EGEC_CORE_SUCCESS) { Client.playerLocal = player; LogU.Debug("QueryPlayer SUCCESS "); LogU.Debug(" player.PlayerId = " + player.PlayerId); LogU.Debug(" player.name = " + player.Name); LogU.Debug(" player.level = " + player.LevelAttrib.Level); LogU.Debug(" player.exp = " + player.LevelAttrib.Exp); LogU.Debug(" player.Money = " + player.Money); LogU.Debug(" player.Diamond = " + player.Diamond); foreach (nicehu.clientcore.Item item in player.Items) { LogU.Debug(" Item: id: {0}, count: {1} ", item.Id, item.Count); } LogU.Debug("playerId :{0}", player.PlayerId); LogU.Debug("player.loginTime :{0}", player.LoginTime); } else { LogU.Debug(" result = " + result); } }
public static IPAddress GetIPV4Address(string hostname) { IPAddress[] hosts = null; try { hosts = Dns.GetHostAddresses(hostname); } catch (Exception ex) { LogU.Error("GetHostAddresses " + ex.Message); return(null); } if (hosts == null || hosts.Length == 0) { return(null); } IPAddress host = null; foreach (IPAddress address in hosts) { if (address.AddressFamily == AddressFamily.InterNetwork) { host = address; break; } } return(host); }
public void OnReceived(Connection connection, byte[] buffer, int offset, int count) { UInt16 MSG_TYPE = BigEndianUtil.ToUInt16(buffer, offset); Int32 msgLength = BigEndianUtil.ToInt32(buffer, offset + 2); if (MSG_TYPE == NHNet.MSG_TYPE_DATA) { connection.OnReceived(connection, buffer, offset + 6, count - 6); } else if (MSG_TYPE == NHNet.MSG_TYPE_DATA_COPMRESS) { //never use byte[] uncompressData = new byte[NHNet._MAX_UNCOMPRESS_MESSAGE_SIZE]; int uncompressDataCount = -1; try { //uncompressDataCount = null;//TODO uncompress } catch (OverflowException ex) { LogU.Debug("uncompress exception {0}", ex.Message); } connection.OnReceived(connection, uncompressData, 0, uncompressDataCount); } }
public Message Deserialize(byte[] buffer, int offset, int size) { if (size <= 4) { return(null); } //java use big endian int curOffset = offset; int restSize = size; MemoryStream baseStream = new MemoryStream(buffer, offset, size); BaseMsg baseMsg = null; try { baseMsg = (BaseMsg)ProtoBuf.Serializer.NonGeneric.Deserialize(typeof(BaseMsg), baseStream); } catch (Exception ex) { LogU.Error(ex.StackTrace); } Message msg = new Message(); msg.Id = baseMsg.id; msg.BaseMsg = baseMsg; return(msg); }
public bool varifyIp(string name = "") { var exits = true; var key = name + "_" + getIp(); //LogU.d("ClientSession - key:" + key); if (clients.ContainsKey(key)) { var time = clients[key]; var timestamp = (DateTime.Now - time).TotalSeconds; //LogU.d("ClientSession - timestamp:" + timestamp); if (timestamp < getFrequent()) { exits = false; } else { clients[key] = DateTime.Now; } } else { LogU.d("ClientSession: key - " + key); clients.TryAdd(key, DateTime.Now); } return(exits); }
private void LogBTN_Click(object sender, EventArgs e) { if (UsernameTXTB.Text != "") { if (PasswordTXTB.Text != "") { try { cln.sendMessage("login"); respuesta = cln.ReceivedMessage(); Console.WriteLine(respuesta); if (respuesta == "\0\u0004send") { LogU user = new LogU() { name = UsernameTXTB.Text, password = PasswordTXTB.Text, }; var serializer = new XmlSerializer(user.GetType()); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); string utf8; using (StringWriter writer = new Utf8StringWriter()) { serializer.Serialize(writer, user, ns); utf8 = writer.ToString(); } cln.sendMessage(utf8); } } catch (Exception ex) { Console.WriteLine(ex.Message); } respuesta = cln.ReceivedMessage(); Console.WriteLine(respuesta); if (respuesta.ToLower() == "\0\u0004true") { PopLBL.Text = "Succesful login!"; this.Refresh(); Transition(); } else if (respuesta.ToLower() == "\0\u0005false") { PopLBL.Text = "Unknown user or password!"; PopLBL.Font = new System.Drawing.Font("hooge 05_55", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); } } else { PopLBL.Text = "Missing data!"; } } else { PopLBL.Text = "Missing data!"; } }
public void ProcessReceive(SocketAsyncEventArgs e, bool firstStep) { if (firstStep) { SocketError socketError = e.SocketError; int bytesTransferred = e.BytesTransferred; EventArgsMgr.PushAppendEventArg(e); if (socketError == SocketError.Success && bytesTransferred > 0) { SocketAsyncEventArgs eventArg = EventArgsMgr.GetEventArg(true); if (eventArg == null) { try { lock (statusLock) { status = NHNet.CON_CLOSED; } socket.Shutdown(SocketShutdown.Both); socket.Disconnect(true); } catch (Exception) { } return; } else { bool willRaiseEvent = socket.ReceiveAsync(eventArg); if (!willRaiseEvent) { ProcessReceive(eventArg, false); } } } return; } if (e.SocketError == SocketError.Success && e.BytesTransferred > 0) { // Data has now been sent and received from the server. if (OnReceived != null) { try { frameDecoder.OnReceived(this, e.Buffer, e.Offset, e.BytesTransferred); } catch (Exception ex) { LogU.Error("ProcessReceive exception {0}", ex.Message); LogU.Error(ex.ToString()); } } EventArgsMgr.PushFreeEventArg(this, e, false); } }
public static void Handle(string[] commands) { nicehu.pb.DeviceInfo deviceInfo = new nicehu.pb.DeviceInfo(); deviceInfo.oSType = "IOS"; deviceInfo.oSType = "9.3.0"; deviceInfo.udid = "default"; deviceInfo.deviceName = "iphone7"; Client.clientCore.create(Client.ip, Client.port, commands[1], commands[2], deviceInfo); LogU.Debug("create " + commands[1] + " " + commands[2]); }
public static void OnReceive(int result) { if (result == (int)EGEC.EGEC_CORE_SUCCESS) { LogU.Debug("AuthToken SUCCESS!!! Keep Connection!"); } else { LogU.Debug("Auth token failed !!! :{0}", result.ToString("X")); } }
public static void OnReceive(int result) { if (result == (int)EGEC.EGEC_CORE_SUCCESS) { LogU.Debug("CreateAccount SUCCESS !"); } else { LogU.Debug("CreateAccount error:" + result.ToString("X")); } }
public void OnMyConnected(Connection connection, SocketError result) { LogU.Debug("Connect ProxyServer: {0}", result); if (result == SocketError.Success) { clientCore.transmitter.Connection = connection; } else { LogU.Debug("Connect ProxyServer Faild !!! :{0}", result.ToString("X")); } }
public static void OnReceive(int result, int accountId, String token, int lastAreaId, List <nicehu.pb.Area> areas) { if (result == (int)EGEC.EGEC_CORE_SUCCESS) { Client.proxyIp = areas[0].ip; Client.proxyPort = areas[0].port; LogU.Debug("Login Success ! ProxyServer address: {0}:{1}", Client.proxyIp, Client.proxyPort); } else { LogU.Debug("Loign error:" + result.ToString("X")); } }
public Object GetPb(Type messageLite) { MemoryStream stream = new MemoryStream(baseMsg.msgData, 0, baseMsg.msgData.Length); Object subPb = null; try { subPb = ProtoBuf.Serializer.NonGeneric.Deserialize(messageLite, stream); } catch (Exception ex) { LogU.Error(ex.StackTrace); } return(subPb); }
public bool handle(Message msg) { OnMessageReceived handleFunction; if (handleFunctions.TryGetValue(msg.Id, out handleFunction)) { handleFunction(msg); return(true); } else { LogU.Error("don't support message id {0}", msg.Id); return(false); } }
public void OnMyReceived(Connection connection, byte[] buffer, int offset, int size) { if (size == -1) { LogU.Debug(" frameDecoder Decode failed then reConnect"); connection.Disconnect(true); clientCore.reConnect(); return; } Message msg = clientCore.Serializer.Deserialize(buffer, offset, size); clientCore.handlerMgr.handle(msg); }
public void OnQueryPlayerRes(Message message) { QueryPlayerRes response = (QueryPlayerRes)message.GetPb(typeof(QueryPlayerRes)); nicehu.clientcore.Player player = new nicehu.clientcore.Player(); if (response.player != null) { player.FromProto(response.player); LogU.Debug("receive QueryPlaeyr Success"); } clientCore.onQueryPlayer( response.result, player ); }
public bool reConnect() { if (connection == null) { LogU.Debug("reconnect found connection is null"); return(false); } if (!connection.HasInit()) { return(false); } connection.ReInit(); connection.Connect(); return(true); }
public void Create(IPEndPoint ipPort, string account, string pass, nicehu.pb.DeviceInfo deviceInfo) { if (clientCore.Connection != null && clientCore.Connection.socket.Connected) { clientCore.Connection.Disconnect(true); } this.account = account; this.pass = pass; this.deviceInfo = deviceInfo; if (deviceInfo == null) { LogU.Error("DeviceInfo is null"); } clientCore.Connection = new Connection(ipPort); clientCore.Connection.OnConnected = OnMyConnected; clientCore.Connection.OnReceived = OnMyReceived; clientCore.Connection.Connect(); }
public void Disconnect(bool isClearData) { try { hasInit = false; socket.Shutdown(SocketShutdown.Both); socket.Disconnect(true); } catch (Exception e) { socket.Close(); LogU.Error("Disconnect exception details {0}", e.Message); } lock (statusLock) { status = NHNet.CON_CLOSED; } }
public bool SendToAuth <T>(Connection connection, T message, int msgId) { if (connection == null) { return(false); } int length = 0; bool result = ClientCore.Serializer.Serialize <T>(ref buffer, ref length, message, msgId, ClientCore.accountId); if (result) { result = connection.Send(buffer, 0, length); } else { LogU.Error("Failed to serialize the message {0}", msgId); } return(result); }
public static void HandleCmd() { if (commands != null && commands[0].Equals("reset")) { lastCmd = ""; LogU.Debug(" Reset SUCCESS"); return; } if (commands != null && commands[0].Equals("nh")) { string easyCmd = GenEasyCmd(); commands = easyCmd.Split(' '); } if (commands == null || commands.Length == 0) { return; } lastCmd = commands[0]; Handle(); commands = null; }
public void Connect() { lock (statusLock) { status = NHNet.CON_CONNECTING; } SocketAsyncEventArgs eventArg = EventArgsMgr.GetEventArg(false); if (eventArg == null) { LogU.Error("Connect----Can't eventArg when connecting"); return; } //无论连接成功还是失败,都会返回true,自动调用ea的Completed时间,不过e中状态不同.当网络问题,导致超时的时候,会返回false,不会自动调用Completed事件.ps: 在createaccount协议中有失败自动重连两次的逻辑 bool willRaiseEvent = socket.ConnectAsync(eventArg); if (!willRaiseEvent) { ProcessConnect(eventArg, false); } }
public bool SendToGame <T>(T message, int msgId) { if (connection == null) { return(false); } int netStatus = connection.getStatus(); //无论什么原因导致连接断开,只要需要发送数据,并且已经初始化过,那么就尝试重连 if (netStatus == NHNet.CON_CLOSED) { if (connection.HasInit()) { clientCore.reConnect(); LogU.Debug("Transmitter: NHNet.CON_CLOSED ,has try reConnect,this msg can not send"); return(false); } } if (netStatus == NHNet.CON_CONNECTING) { LogU.Debug("Transmitter: NHNet.CON_CONNECTING ,can not send data"); return(false); } int length = 0; bool result = ClientCore.Serializer.Serialize <T>(ref buffer, ref length, message, msgId, ClientCore.accountId); if (result) { result = connection.Send(buffer, 0, length); } else { LogU.Error("Failed to serialize the message {0}", msgId); } return(result); }
public bool Send(byte[] buffer, int offset, int count) { SocketAsyncEventArgs eventArg = EventArgsMgr.GetEventArg(false); if (eventArg == null) { LogU.Error("There is no SocketAsyncEventArgs available"); return(false); } if (bufferMgr.SetBuffer(eventArg, buffer, offset, count) == false) { LogU.Error("There is no memory available in buffermanager"); return(false); } bool willRaiseEvent = socket.SendAsync(eventArg); if (!willRaiseEvent) { ProcessSend(eventArg, false); } return(true); }
public void ReInit() { try { socket.Close(); this.netHandler = new NetworkHandler(); this.frameDecoder = new LengthFieldBasedFrameDecoder(NHNet._MAX_COMPRESS_MESSAGE_SIZE, 2, 4, 0, 0); this.bufferMgr = new BufferMgr(); lock (eventLock) { this.EventArgsMgr = new EventArgsMgr(this); evenCount = 0; } this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); this.socket.NoDelay = true; this.status = NHNet.CON_CLOSED; } catch (Exception ex) { LogU.Warn("reInitConection exception {0}", ex.ToString()); } }
public void HandleAsyncEvent(SocketAsyncEventArgs e, Boolean firstStep) { switch (e.LastOperation) { case SocketAsyncOperation.Connect: //LogU.Debug("Receive SocketAsyncOperation.Connect"); ProcessConnect(e, firstStep); break; case SocketAsyncOperation.Receive: //LogU.Debug("Receive SocketAsyncOperation.Receive {0}", e.BytesTransferred); ProcessReceive(e, firstStep); break; case SocketAsyncOperation.Send: //LogU.Debug("Receive SocketAsyncOperation.Send"); ProcessSend(e, firstStep); break; default: LogU.Error("Invalid operation completed"); throw new Exception("Invalid operation completed"); } }
public static void Handle(string[] commands) { Client.clientCore.authToken(); LogU.Debug("authToken "); }