Search code examples
javasocketslibgdxclient-serverhole-punching

libGDX client (server) client connection


I am trying to create a multiplayer game. I think there are three possible ways to do this:

1. Port Forwarding

Only a few people will open a port on their router.

2. UDP / TCP hole punching

This is verry ccomplicated and will not work with every router / NAT.

3. Relay Server

I think this is the easiest method to accomplish a multiplayer. So my plan is to establish a socket connection to a PHP server which will also have a socket connection with the other player and passes the data.

At the time I have a client part and a test server part in Java:

SocketHints hints = new SocketHints();
Socket client = Gdx.net.newClientSocket(Net.Protocol.TCP, textfield.getText(), 9021, hints);
       try {
               client.getOutputStream().write((textfield2.getText() + "\n").getBytes());
           } catch (IOException e) {
                e.printStackTrace();
           }

And

new Thread(new Runnable() {
        @Override
        public void run() {
            ServerSocketHints serverSocketHint = new ServerSocketHints();
            serverSocketHint.acceptTimeout = 0;
            ServerSocket serverSocket = Gdx.net.newServerSocket(Net.Protocol.TCP, 9021, serverSocketHint);
            while (true) {
                Socket socket = serverSocket.accept(null);
                BufferedReader buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                try {
                    status += "Receiving message: \"" + buffer.readLine() + "\"\n\n";
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

How can I receive data from the socket connection from the client?

And is there maybe a better way to do this?


Solution

  • So, you want to make a socket server from PHP? I'm not recommending it. Try to use kryonet. It's a java Socket Client & Server with an easy way to use in Java.

    If you want to make the server online, run the Kryonet Socket Server on your Server with available public IP.