It looks like I need the help of the GDNet community once more.
So recently I started learning some basic network programming in games. I am currently creating a game where the same program can act as both a client and host a multiplayer session. I am only doing LAN communication atm using direct IP address input (the user has to enter the IP address of the host of the game in order to join).
I implemented basic TCP connection in .Net using the System.Net.Sockets.TcpListener/TcpClient classes, and managed to establish a connection between 2 computers in my house. However, when I try to write data to the NetworkStream returned by TcpClient.GetStream() method (specifically 44 bytes, if it makes a difference) I do not receive input on my other end.
I tried using the same computer as both the Host and the Client by launching two instances of my program, and using 3 different packet analyzers to try to track the packets, however I find that nothing shows, not even the handshake establishment... (is this because of loopback, perhaps?) I did not try to track packets between two different PCs.
Questions:
- Can I track packets on a loopback address? If yes, what program does it?
- Perhaps the amount of data I'm writiing is not large enough to send the packet? Can I overcome this and send exactly 44 bytes anyway?
- From the code below, am I even doing it right?
Object declarations:
[source lang="csharp"]me = new IPEndPoint(MyIpAddress, port);
tcpl = new TcpListener(me);
tcpl.ExclusiveAddressUse = false;
tcpc = new TcpClient();
tcpc.ExclusiveAddressUse = false;
players = new List<TcpClient>();[/source]
Connection Establishment:
[source lang="csharp"]// hosting is True if the user choses to host a game
if (hosting)
{
tcpl.Start(); // start listening on the port specified
while (!tcpl.Pending())
System.Threading.Thread.Sleep(2); // just waiting, will be replaced later with something better
while (tcpl.Pending())
players.Add(tcpl.AcceptTcpClient()); // accept a tcp connection request
tcpl.Stop(); // stop listening
}
else // the user wants to join a hosted game
{
tcpc.Connect(HostIpAddress, port); // ask for connection from host
}[/source]
Later, data send & receive:
[source lang="csharp"]if (hosting)
{
byte[] data = new byte[44];
// here data gets initialized...
foreach (TcpClient player in players)
player.GetStream().Write(data, 0, data.Length);
}
else // read data
{
NetworkStream stream = tcpc.GetStream();
byte[] data = new byte[44];
stream.Read(data, 0, 44);
// working with data here...
}[/source]