2
votes

I'm currently trying to make an online video game, which currently uses TCP to send packets. I want to use UDP, but I'm extremely new to UDP and I'm having some issues.

When I test my server/client(s) on the same computer (localhost), the packets seem to be interfering with each other.

For example, if the client sends a packet to the server (UDP, 127.0.0.1:1338), the client ends up receiving the packet, since the client is also listening for packets from 127.0.0.1 on port 1338. Similarly, when I try to test 2 clients and 1 server, the clients may send out packets which are meant for the server, but are picked up by the other client.

How can I test UDP on localhost since all packets are being received from/sent to 127.0.0.1:1338? Do I need to implement some sort of layer in my packets that distinguishes if the packet is meant for the server, or a specific client?

3

3 Answers

3
votes

An additional layer will not help - because the server may never actually get the packet.

Make the ports on the server and client configurable. That way you could have different ports on the same machine for testing and change it when going to production. Just remember you need to configure both ports in both the client and server. This is a good practice anyway.

You still have another problem - of several clients residing on the same machine and listening to the same port. You can have a random port for each client (the client selects one in random and then notifies the server). Or you can try binding to different IP addresses (one will use 127.0.0.1 an another will use the real IP of the PC), but it's not extensible.

4
votes

Only your Server should listen on the defined port number (1338). Each client should select a free port number and send the server this port number. The server has to store the client information and send then the packets to the clients in this client list.

The clients should also send a goodby packet when the client is closing to know on the server side which clients are still available and which aren't participating anymore.

You should also implement some kind of housekeeping in this client list. For example store the timestamp of the last received packet from the client and remove clients that haven't sent data for some time (crashed client, lost connection ...) from the list.

0
votes

If you are going to use this in a LAN setup, then you can always filter the received packet based on the sender's address -- recvmsg() of UDP allows you to retrieve sender's address and port number. If you are going to use this in a WAN setup, then this likely would not be an issue unless you are trying to do multicast. And, even with multicast, duplciate packets are not send back to the receiver. You can use IP_MULTICAST_LOOP to disable this option.