Java-Client PHP-Server UDP Hole Punching example code

后端 未结 1 399
野趣味
野趣味 2021-01-23 06:23

I\'m working on a project that will require ea p2p server, but I haven\'t found any java-client php-server example code. I understand the concept of how udp hole punching works

相关标签:
1条回答
  • 2021-01-23 07:03

    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 :)

    0 讨论(0)
提交回复
热议问题