protected DateTime m_send_heartbeat_time; // Time of send heart beat // Init bean, support server address public bool Init(string strSrvIP, int nSrvPort) { CSLogger.Init(); m_server_ip = strSrvIP; m_server_port = nSrvPort; return(true); }
// conn thread function private void ConnThread() { CSLogger.LogDebug("Enter ConnThread"); try { IPAddress ip_address = null; IPAddress[] ip_array = Dns.GetHostAddresses(m_host); foreach (IPAddress ip in ip_array) { if (ip.AddressFamily == AddressFamily.InterNetwork) { ip_address = ip; break; } } IPEndPoint ip_end_point = new IPEndPoint(ip_address, m_port); m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_socket.Blocking = true; m_socket.Connect(ip_end_point); m_recv_stream = new MemoryStream(); m_recv_thread = new Thread(new ThreadStart(RecvThread)); m_send_thread = new Thread(new ThreadStart(SendThread)); m_recv_thread.Start(); m_send_thread.Start(); m_conn_thread = null; } catch (System.Exception ex) { CSLogger.LogError(ex.ToString()); } CSLogger.LogDebug("Exit ConnThread"); }
// recv thread function private void RecvThread() { CSLogger.LogDebug("Enter RecvThread"); try { while (true) { if (m_socket == null || m_socket.Connected == false) { m_recv_thread = null; break; } ParseProcotol(); System.Threading.Thread.Sleep(10); } } catch (SocketException /*e*/) { CSLogger.LogDebug("RecvThread: SocketException "); } catch (Exception /*e*/) { CSLogger.LogDebug("RecvThread: Exception "); } CSLogger.LogDebug("Exit RecvThread"); }
// Disconnect public void Disconnect() { CSLogger.LogNotice("Disconnect " + m_server_ip + ":" + m_server_port); if (null != m_server_socket) { m_server_socket.DisConnect(true); } }
// Parse a protocol. private void ParseProcotol() { // Check recv len int socket_recv_len = m_socket.Receive(m_recv_buff, SocketFlags.None); if (socket_recv_len <= 0) { return; } // Check pos m_recv_stream.Position = m_recv_stream.Length; m_recv_stream.Write(m_recv_buff, 0, socket_recv_len); m_recv_stream.Position = m_recv_stream_pos; while (m_recv_stream.Length - m_recv_stream.Position >= Message.MSG_BASIC_LEN) { m_recv_stream_pos = m_recv_stream.Position; m_recv_stream.Read(m_recv_buff, 0, Message.MSG_BASIC_LEN); MBinaryReader mbr = new MBinaryReader(m_recv_buff); int msg_len = mbr.ReadUInt16(); if (m_recv_stream.Length - m_recv_stream.Position >= msg_len - Message.MSG_BASIC_LEN) { m_recv_stream_pos = 0; m_recv_stream.Read(m_recv_buff, 0, msg_len - Message.MSG_BASIC_LEN); mbr = new MBinaryReader(m_recv_buff); ushort msg_id = mbr.ReadUInt16(); Message msg = MessageFactory.CreateMessageById(msg_id); if (null == msg) { CSLogger.LogNotice("Invalid msg id: " + msg_id); } if (!msg.FromBytes(mbr)) { CSLogger.LogNotice("ParseProcotol: Fail to parse msg: " + msg.ToString()); } if (m_recv_queue != null) { lock (m_recv_queue) { m_recv_queue.Enqueue(msg); } } } else { m_recv_stream.Position = m_recv_stream_pos; break; } mbr.Close(); mbr = null; } if (m_recv_stream.Position == m_recv_stream.Length) { m_recv_stream.SetLength(0); } }
// send thread function private void SendThread() { CSLogger.LogDebug("Enter SendThread"); try { Message msg = null; while (true) { if (m_socket == null || m_socket.Connected == false) { m_send_thread = null; break; } m_event_wait_send.WaitOne(); m_event_wait_send.Reset(); lock (m_send_queue) { while (m_send_queue.Count > 0) { msg = m_send_queue.Peek(); byte[] bytes = msg.ToBytes(); int result = 0; int byte_size = bytes.Length; while (result != byte_size) { try { result += m_socket.Send(bytes, result, byte_size - result, SocketFlags.None); } catch (System.Exception ex) { CSLogger.LogError(ex.ToString()); } } m_send_queue.Dequeue(); } } System.Threading.Thread.Sleep(10); } } catch (SocketException /*e*/) { CSLogger.LogDebug("SendThread: SocketException "); } catch (Exception /*e*/) { CSLogger.LogDebug("SendThread: Exception "); } CSLogger.LogDebug("Exit SendThread"); }
// Get message from queue public Message GetMessage() { Message msg = null; if (m_recv_queue != null && m_recv_queue.Count > 0) { lock (m_recv_queue) { msg = m_recv_queue.Dequeue(); CSLogger.LogDebug("Receive msg:" + msg.ToString()); } } return(msg); }
public static void Main(string[] args) { // Init logger CSLogger.Init(); // Verify protocol. VerifyProtocolParse.RunTest(); // Default assign server string strServerIP = "127.0.0.1"; int nServerPort = 7001; // Create a player and run it CSGatePlayer hPlayer = new CSGatePlayer(); hPlayer.RunGatePlayer(strServerIP, nServerPort); }
// Send msg public void SendMsg(Message msg) { if (!IsConnected()) { CSLogger.LogError("GateServer is disconnected when send " + msg.ToString()); return; } CSLogger.LogNotice("Send Msg: " + msg.ToString()); lock (m_send_queue) { m_send_queue.Enqueue(msg); } m_event_wait_send.Set(); }
// Called this function in loop public void Update() { if (null == m_server_socket) { return; } if (!m_server_socket.IsConnected()) { CSLogger.LogError("Socket is disconnected, please re-connect it"); return; } Message msg = m_server_socket.GetMessage(); base.DispatchMsg(msg); // Try to Send heart beat msg TimerSendHeartBeatMsg(); }
// connect to a server public void Connect(string host, int port) { DisConnect(false); m_recv_queue = new Queue <Message>(); m_host = host; m_port = port; try { m_conn_thread = new Thread(new ThreadStart(ConnThread)); m_conn_thread.Start(); } catch (Exception /*e*/) { CSLogger.LogError("Connect: Exception"); } }
// Msg dispatch function protected bool DispatchMsg(Message msg) { if (null == msg) { return(false); } if (msg.msg_id == GC_HeartBeat_Msg.MSG_ID) { return(OnGC_HeartBeat_Msg((GC_HeartBeat_Msg)msg)); } if (msg.msg_id == GC_Echo_Response.MSG_ID) { return(OnGC_Echo_Response((GC_Echo_Response)msg)); } if (msg.msg_id == GC_Chat_Msg.MSG_ID) { return(OnGC_Chat_Msg((GC_Chat_Msg)msg)); } CSLogger.LogError("Recv invalid msg id from GateServer: " + msg.msg_id); return(false); }
// Send msg to server public void SendMsgToServer(Message msg) { if (m_server_socket == null) { return; } if (!m_server_socket.IsConnected()) { CSLogger.LogNotice("Server Is DisConnected"); return; } if (null == msg) { CSLogger.LogError("SendMsgToServer: null == msg"); return; } if (null == m_server_socket) { CSLogger.LogError("SendMsgToServer: null == m_gs_socket"); return; } CSLogger.LogDebug("SendMsgToServer: " + msg.ToString()); m_server_socket.SendMsg(msg); }
// run this player public void RunGatePlayer(string strSrvIP, int nSrvPort) { if (!Init(strSrvIP, nSrvPort)) { return; } AsyncConnect(); // Max try count: 1000 DateTime loop_begin_time = DateTime.Now; for (int i = 0; i < 1000; ++i) { if (IsServerConnected()) { OnAsyncConnectSuccess(); break; } System.Threading.Thread.Sleep(2); TimeSpan time_span = DateTime.Now - loop_begin_time; if (time_span.TotalSeconds >= 3.0f) { break; } } if (!IsServerConnected()) { CSLogger.LogNotice("Connected failed"); OnAsyncConnectFailed(); return; } // Main loop while (true) { Update(); } }
// Default handle of msg: GC_Echo_Response protected virtual bool OnGC_Echo_Response(GC_Echo_Response msg) { CSLogger.LogDebug("ServerMsgHandler: Recv msg: [" + msg.ToString() + "]"); return(false); }
// Default handle of msg: GC_Chat_Msg protected virtual bool OnGC_Chat_Msg(GC_Chat_Msg msg) { CSLogger.LogDebug("ServerMsgHandler: Recv msg: [" + msg.ToString() + "]"); return(false); }
// Called after connect success public void OnAsyncConnectSuccess() { CSLogger.LogNotice("Success to connect " + m_server_ip + ":" + m_server_port); m_heartbeat_index = 0; m_send_heartbeat_time = DateTime.UtcNow; }
// Default handle of msg: GC_HeartBeat_Msg protected override bool OnGC_HeartBeat_Msg(GC_HeartBeat_Msg msg) { CSLogger.LogNotice("Receive HB: " + msg.heartbeat_index); return(false); }