Exemplo n.º 1
0
        /// <summary>
        /// Message that the host sends when a new peer has connected to the game,
        /// contains new peer ID and address which to connect
        /// </summary>
        static public byte[] Build_NewConnectedPeer(PlayerInfo newPeer)
        {
            List <byte> data = new List <byte>();

            data.AddRange(BitConverter.GetBytes((int)MessageType.NewPeer));
            data.AddRange(BitConverter.GetBytes(newPeer.PeerID));
            byte[] address = newPeer.GetPlayerAddress();
            data.AddRange(BitConverter.GetBytes(address.Length));
            data.AddRange(address);
            return(data.ToArray());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Accept a connection attempt
        /// </summary>
        private void AcceptCallback(IAsyncResult ar)
        {
            try {
                Socket listener = (Socket)ar.AsyncState;
                Socket newPeer  = listener.EndAccept(ar);

                PlayerInfo newPlayer = new PlayerInfo(nextID, newPeer);
                byte[]     data      = new byte[1024];

                if (isHost && peerList.Count != 0)
                {
                    Console.WriteLine("As host update other players of the newly connected peer with address{0}", newPlayer.GetPlayerAddress());
                    data = PacketBuilder.Build_NewConnectedPeer(newPlayer);
                    Broadcast(data);
                }

                // Save player connection
                Console.WriteLine("Saving connection, nextID:{0}", nextID);
                peerList.Add(nextID, newPlayer);

                newPeer.BeginReceive(buff, 0, buff.Length, 0, ReceiveCallback, newPeer);
                ++nextID;

                listener.BeginAccept(AcceptCallback, listener);
            }
            catch (SocketException ex) {
                GameForm.ShowErrorDialog(ex.Message);
            }
            catch (ObjectDisposedException ex) {
                GameForm.ShowErrorDialog(ex.Message);
            }
        }