public void SendServerInformation(Peer destinationPeer) { using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(memStream)) { writer.Write(CurrentUser); writer.Write(peers.Count((Peer p) => { return p.isLoggedIn; }) + peersToAdd.Count((Peer p) => { return p.isLoggedIn; })); foreach (Peer peer in peers) { if (peer.isLoggedIn) { writer.Write(peer.Address.Address.ToString()); writer.Write(peer.listenPort); writer.Write(peer.name); } } foreach (Peer peer in peersToAdd) { if (peer.isLoggedIn) { writer.Write(peer.Address.Address.ToString()); writer.Write(peer.listenPort); writer.Write(peer.name); } } destinationPeer.SendData(P2PNotices.ServerGameInformation, memStream.ToArray()); } } }
void OnServerInformationReceived(byte[] data) { using (System.IO.MemoryStream readStream = new System.IO.MemoryStream(data)) { using (System.IO.BinaryReader reader = new System.IO.BinaryReader(readStream)) { ServerPeer.name = reader.ReadString(); int peerCount = reader.ReadInt32(); for (int i = 0; i < peerCount; ++i) { string address = reader.ReadString(); int port = reader.ReadInt32(); string username = reader.ReadString(); Peer peer = new Peer(new IPEndPoint(IPAddress.Parse(address), port), true); peer.name = username; using (System.IO.MemoryStream writeStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(writeStream)) { writer.Write(CurrentUser); peer.SendData(P2PNotices.PeerConnect, writeStream.ToArray()); } } peer.isLoggedIn = true; peer.isConnected = true; peersToAdd.Add(peer); } } } if (JoinedGame != null) JoinedGame(this, peers.Union(peersToAdd).ToList()); }
public void ConnectToServer(IPAddress ip, int port) { ServerIP = new IPEndPoint(ip, port); Peer peer = new Peer(ServerIP, true); ServerPeer = peer; AddPeer(peer); peer.isConnected = true; using (System.IO.MemoryStream memStream = new System.IO.MemoryStream()) { using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(memStream)) { writer.Write(((IPEndPoint)listener.LocalEndpoint).Port); writer.Write(CurrentUser); byte[] bytes = memStream.ToArray(); ServerPeer.SendData(P2PNotices.ClientJoinRequest, bytes); } } }