3
\$\begingroup\$

So - my whole knowledge comes from google and stackoverflow. I'm trying to create an UDP server (with two slots per new instance of the game) and clients.

My problem is here that I totally don't know where to start. I can't find and tutorial that shows how to connect two players with a server via UDP - and yes - it has to be UDP cause of the game mechanics. I wrote this:

public class Server {

   private static HashSet<Integer> ports = new HashSet<Integer>(); // these     are player's IDs
   static ArrayList<InetAddress> addresses = new ArrayList<InetAddress>(); 
   public static boolean player1_active = false, player2_active = false;
   public static PlayerCredits p1, p2, temp;
   public static void main(String[] args) throws Exception {

   // The default port     
    int serverport = 8888;        


    DatagramSocket udpServerSocket = new DatagramSocket(serverport);        
        DatagramPacket sendpacket;
    System.out.println("Server started...\n");

    while(true)
    {

        byte[] receiveData = new byte[1024];          


        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);


        udpServerSocket.receive(receivePacket);           


        String clientMessage = (new String(receivePacket.getData())).trim();


        System.out.println("Client Connected - Socket Address: " + receivePacket.getSocketAddress());
        System.out.println("Client message: \"" + clientMessage + "\"");          


        InetAddress clientIP = receivePacket.getAddress();           
                    addresses.add(clientIP);

        System.out.println("Client IP Address & Hostname: " + clientIP + ", " + clientIP.getHostName() + "\n");

        // Get the port number which the recieved connection came from
        int clientport = receivePacket.getPort();
        System.out.println("Adding "+clientport);
        ports.add(clientport);

        // Response message         
        String returnMessage = clientMessage.toUpperCase();          
        System.out.println(returnMessage);
        // Create an empty buffer/array of bytes to send back 
        byte[] sendData  = new byte[1024];




                    temp = new PlayerCredits(clientport, clientIP);

                    if(!player1_active){
                     p1 = new PlayerCredits(clientport, clientIP);
                     player1_active = true;
                    }

                    if(temp.port != p1.port && temp.ad != p1.ad)
                     if(!player2_active){
                        p2 = new PlayerCredits(clientport, clientIP);
                        player2_active = true;
                    }

                    DatagramPacket sendPacket;
                     if(p2 == null){
                         String awaiting = "WAITING FOR SECOND PLAYER";
                         sendData = awaiting.getBytes();
                          sendPacket= new DatagramPacket(sendData, sendData.length, p1.ad, p1.port); 
                            udpServerSocket.send(sendPacket);   
                     }
                         else{
                         String awaiting = "SECOND PLAYER INCOMING";
                         sendData = awaiting.getBytes();
                            if(p2!=null){
                            sendPacket = new DatagramPacket(sendData, sendData.length, p2.ad, p2.port); 
                            udpServerSocket.send(sendPacket);   
                            }
                            sendPacket = new DatagramPacket(sendData, sendData.length, p1.ad, p1.port); 
                            udpServerSocket.send(sendPacket);    
                     }

        }

}
public static class PlayerCredits{
    int port;
    InetAddress ad;
    public PlayerCredits(int p, InetAddress a){
        this.port = p;
        this.ad = a;
    }
}

So - for now I have two people connected - but as you will probably say - it's WRONG. Cause I know - it is :D I need to somehow implement every player on the Multisocket or something (or connect them via TCP and then listen on a new thread with a new datagram).

If there is someone that could help and tell me, how it should be done like in 3 steps like (I don't need code):

  1. Connection with TCP
  2. Create new threads with players and listen on UDP
  3. Start the game when 2 players are connected

Also, how to stop the 'third connection' and redirect it to a new game instance? (cause it's 1v1).

I would be so grateful. I will have networking in two years in college, but I want to learn it.

\$\endgroup\$
2
\$\begingroup\$

The reason for the roadblock you are hitting is that you try to do something which does not exist. As a stateless protocol, UDP doesn't have "connections".

Because a UDP datagram is not explicitly tied to a connection, you need to find out by yourself from which client an UDP datagram originates. One way to do this is by calling getPort() and getAddress on the DatagramPacket and use that information to find out from which player it originates.

When you then want to forward the information from that datagram to the other players, you send them new datagrams with their respective ports and address of those players.

Because UDP is stateless, you need to implement your own state management to keep track of which players are currently connected. A good way to do this is by having some collection of currently connected players. When you receive a new message, check if a player with that IP and port is already in the collection. If not, add them. Remove players when they send a special "disconnect" message or when they didn't sent any messages for X seconds (timeout).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy