private void _connectCallBack(IAsyncResult result) { try { _socket.EndConnect(result); OnConnect(true); _socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, _receivedCallBack, _socket); //处理多线程 可以不使用多线程发送 服务器一般使用 if (UsedThread) { ProcessThread = new Thread(this.UpdateProcess); ProcessThread.IsBackground = true; ProcessThread.Start(); } } catch (Exception ex) { Debuger.DebugLog(ex.Message); OnConnect(false); if (UsedThread) { Update(); } } }
/// <summary> /// 接收到消息 /// </summary> /// <param name="client"></param> /// <param name="msg"></param> public virtual void OnReceivedMessag(Client client, Message msg) { client.LastMessageTime = DateTime.UtcNow; if (msg.Class == MessageClass.Ping) { SendMessage(client, msg); } else if (msg.Class == MessageClass.Package) { var package = MessageBufferPackage.ParseFromMessage(msg); foreach (var i in package.Messages) { OnReceivedMessag(client, i); } } else if (msg.Class == MessageClass.Action) { client.SetActionMessage(msg); } else if (this.HandlerManager != null) { this.HandlerManager.Handle(msg, client); } else { Debuger.DebugLog("Server No Handler!"); } }
public void Start() { OnStart(); IsWorking = true; CurrentConnectionManager.Clear(); _socket = new Socket(IPAddress.Any.AddressFamily, SocketType.Stream, ProtocolType.Tcp); //_socket.SendTimeout = 999; //_socket.ReceiveTimeout = 999; _socket.LingerState = new LingerOption(true, 10); _socket.Bind(new IPEndPoint(IPAddress.Any, Port)); _socket.Listen(2000); AcceptThread = new Thread(new ThreadStart(ThreadRun)); AcceptThread.IsBackground = true; AcceptThread.Start(); SendThread = new Thread(new ThreadStart(SendMessage)); SendThread.IsBackground = true; SendThread.Start(); Debuger.DebugLog("Server Listen at port:" + Port); }
private void HandleException(Client client, Exception ex) { Debuger.DebugLog(ex.Message); RemoveClient(client); }