Reputation: 354
I'm creating a game server for a University project so I'm doing this without using any libraries / frameworks.
After a lot of research I want the client and server to do the bulk of communication such as character movement and timers using the UDP protocol as the reliability of this aspect of the game is not so important and lost packets can be compensated for.
But I also want to use the TCP protocol for some other aspects of the game such as actions and events where it is critical the information reaches the client.
My problem is that I don't know much about using UDP in general and in Java, from my understanding it is completely different to just having an open Socket object for TCP. I'm thinking that the initial connection between the client and server will be done by TCP then once this connection has been established should the server send a port number back to the client that the client will use to communicate with the server via UDP?
Which brings me to the issue of having multiple clients, do they all need to be allocated different port numbers to connect via UDP to the server? So the server will have 1 different port number for each client connected?
My plan for the server is to have for every client connected 1 sending thread and 1 receiving thread - would I be able to handle both TCP and UDP communications in each of these threads or would there need to be 4 threads for each client with 2 for tcp and 2 for udp?
Again these are just my first thoughts and I don't know much about UDP so sorry if I've got the complete wrong end of the stick! Thanks if anyone can help with any of this though!
Upvotes: 1
Views: 1266
Reputation: 51
Should the server send a port number back to the client that the client will use to communicate with the server via UDP?
You can do this, or you can load it from a properties file. Depends on your implementation.
Do [multiple clients] all need to be allocated different port numbers to connect via UDP to the server? So the server will have 1 different port number for each client connected?
No. A server can differentiate which client a packet belongs to from the IP address on the Datagram (UDP) packet that was received.
Would I be able to handle both TCP and UDP communications in each of these threads or would there need to be 4 threads for each client with 2 for tcp and 2 for udp?
You do not need a separate thread for sending data, because this doesn't cause the thread to block. Only receiving causes the thread to block, so your client program would only need 2 communication threads; One to receive TCP, and another to receive UDP communications.
NOTE: Java does handle TCP and UDP communications quite differently. TCP is a stream that you write to (which automatically handles handshaking and packet lose for you), while UDP uses a DatagramPacket object that is populated with bytes and sent.
Upvotes: 1