private void AcceptCallback(IAsyncResult ar) { ClientConnection client = null; try { Socket s = (Socket)ar.AsyncState; client = new ClientConnection() { PacketProcessor = new PacketProcessor(), socket = s.EndAccept(ar), buffer = new byte[BUFFER_SIZE] }; lock (mConnectionList) { mConnectionList.Add(client); } //queue up incoming receive data connection client.socket.BeginReceive(client.buffer, 0, client.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client); //start accepting connections again listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); client.fullAddress = string.Format("{0}:{1}", (client.socket.RemoteEndPoint as IPEndPoint).Address, (client.socket.RemoteEndPoint as IPEndPoint).Port); Console.WriteLine(client.GetFullAddress()); } catch (Exception) { if (client.socket == null) { client.socket.Close(); lock (mConnectionList) { mConnectionList.Remove(client); } } listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); } }
private void ReceiveCallBack(IAsyncResult ar) { //need to setup buffer of length PacketController // Retrieve the state object and the handler socket // from the asynchronous state object. ClientConnection client = (ClientConnection)ar.AsyncState; try { int bytesRead = client.socket.EndReceive(ar); Console.WriteLine("bytes read" + bytesRead); //allows to pause traffic and restart for debugging purposes. bytesRead += client.lastPartialSize; if (bytesRead > 0) { int offset = 0; //build/compile packets until can no longer or data is finished while (client.socket.Connected) { BasePacket basePacket = BuildPacket(ref offset, client.buffer, bytesRead); if (basePacket == null) { break; } else { client.PacketProcessor.ProcessPacket(client, basePacket); } } //Not all bytes consumed, transfer leftover to beginning if (offset < bytesRead) { Array.Copy(client.buffer, offset, client.buffer, 0, bytesRead - offset); } Array.Clear(client.buffer, bytesRead - offset, client.buffer.Length - (bytesRead - offset)); //allows to pause traffic and restart for debugging purposes. client.lastPartialSize = bytesRead - offset; //Build any queued subpackets into basepackets and send client.FlushQueuedSendPackets(); if (offset < bytesRead) //need offset since not all bytes consumed { client.socket.BeginReceive(client.buffer, bytesRead - offset, client.buffer.Length - (bytesRead - offset), SocketFlags.None, new AsyncCallback(ReceiveCallBack), client); } else { client.socket.BeginReceive(client.buffer, 0, client.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client); } } else { Console.WriteLine("Client at {0} has disconnected", client.GetFullAddress()); lock (mConnectionList) { client.Disconnect(); mConnectionList.Remove(client); } } } catch (SocketException) { if (client.socket != null) { client.socket.Disconnect(false); Console.WriteLine("Client at {0} has disconnected", client.GetFullAddress()); lock (mConnectionList) { mConnectionList.Remove(client); } } } }