public void OnAcceptComplate(object sender, SocketAsyncEventArgs e) { if (listening == false) { return; } if (e.AcceptSocket == null) { return; } MTCPSocketHandler clientHandler = new MTCPSocketHandler { workSocket = e.AcceptSocket }; int serial = clientHandler.workSocket.Handle.ToInt32(); socketHandlers.Add(serial, clientHandler); defaultEngine.OnConnect(serial); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.SetBuffer(clientHandler.buffer, 0, MTCPSocketHandler.maxBufferSize); args.UserToken = clientHandler; args.Completed += OnReceiveComplate; clientHandler.workSocket.ReceiveAsync(args); e.AcceptSocket = null; listener.AcceptAsync(e); }
public override bool Initialize() { handler = new MTCPSocketHandler { workSocket = new Socket(SocketType.Stream, ProtocolType.Tcp) }; return(true); }
public void Send(Socket client, byte[] buffer) { MTCPSocketHandler handler = socketHandlers[client.Handle.ToInt32()]; if (handler != null) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.SetBuffer(buffer, 0, buffer.Length); args.Completed += OnSendComplate; args.UserToken = handler; client.SendAsync(args); } }
public void OnReceiveComplate(object sender, SocketAsyncEventArgs e) { if (receiving == false) { return; } Socket client = (Socket)sender; MTCPSocketHandler handler = (MTCPSocketHandler)e.UserToken; // Success if (client.Connected && e.BytesTransferred > 0) { BasePacket receiveDataPacket = defaultEngine.packetDistinctioner.Distinction(handler.buffer); if (receiveDataPacket == null) { client.ReceiveAsync(e); return; } receiveDataPacket.Serial = client.Handle.ToInt32(); defaultEngine.Dispatcher.Dispatch(receiveDataPacket); client.ReceiveAsync(e); return; } // Fail client.Disconnect(false); client.Dispose(); int serial = client.Handle.ToInt32(); socketHandlers.Remove(serial); defaultEngine.OnDisconnect(serial); }