Beispiel #1
0
        //first recieve fails not sure why
        private void Receive()
        {
            socket.BeginReceiveFrom(PacketBuffer, 0, BufferSize, SocketFlags.None, ref ClientEndpoint, AsReceive = (ar) =>
            {
                AsyncBuffer so = (AsyncBuffer)ar.AsyncState;
                int bytes      = socket.EndReceiveFrom(ar, ref ClientEndpoint);
                socket.BeginReceiveFrom(so.Buffer, 0, BufferSize, SocketFlags.None, ref ClientEndpoint, AsReceive, so);
                byte[] tempBuff = new byte[bytes];
                Array.Copy(so.Buffer, 0, tempBuff, 0, tempBuff.Length);

                Client TargetClient = null;
                //Check if client is already connected
                if (ConnectedClients.Where(x => x.endPoint.Equals(ClientEndpoint)).Count() == 0)
                {
                    Console.WriteLine("New client connected " + ClientEndpoint.ToString());
                    TargetClient = new Client(ClientEndpoint);
                    ConnectedClients.Add(TargetClient);
                }
                else
                {
                    TargetClient = ConnectedClients.Where(x => x.endPoint.Equals(ClientEndpoint)).First();
                }

                Packet packet = new Packet(tempBuff);
                if (packet.IsValid)
                {
                    Console.WriteLine("Recieved " + packet.ToString());
                    socket.SendTo(TargetClient.HandlePacket(packet), ClientEndpoint);
                }
            }, AsBuffer);
        }