Java-Client PHP-Server UDP Hole Punching example code

北战南征 提交于 2019-12-02 01:00:55

I was facing a similar problem. And was trying to solve it in a similar way.

Some parts of your code look wrong to me. Sockets in Java are made for TCP but the title says UDP. Therefore u should use DatagramSockets. But then we come to the point where i stuck too. HTTP-Requests use tcp as well, so opening the port with HTTP might lead to a corrupt port, after tcp session was closed. (Just a guess)


public class Main {

    public static void main(String[] args) {

        try
        {

            String httpRequest = "GET /index.php HTTP/1.1\n" +
                    "Host: <PHP SERVER NAME HERE>";

            InetAddress IPAddress = InetAddress.getByName(<PHP SERVER IP HERE>);

            DatagramSocket clientSocket = new DatagramSocket();
            byte[] sendData = new byte[1024];
            byte[] receiveData = new byte[1024];
            String sentence = httpRequest;
            sendData = sentence.getBytes();

            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 80);
            clientSocket.send(sendPacket);
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientSocket.receive(receivePacket);

            String modifiedSentence = new String(receivePacket.getData());
            System.out.println("FROM SERVER:" + modifiedSentence);

            clientSocket.close();

        }catch(Exception e){e.printStackTrace();}

    }


}

The Code above theoretically sents a HTTP over UDP request. So that the displayed Port will be the UDP one. In my case i didnt get any response from the PHP Server and stuck at clientSocket.recieve(..) . I guess because the firewall of my webserver is blocking udp packets. If the code works by anyone i would proceed like this:

  1. save all accessing ips and ports to a DB and list them to the other client.
  2. Write ur Data in DatagramPackets like above to the other client.

I hope this may help. If anyone can get it completly working i would also be interested in it :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!