Java客户端PHP-Server UDP打孔示例代码

我正在开发一个需要ea p2p服务器的项目,但我还没有找到任何java-client php-server示例代码。 我理解udp打孔如何工作的概念,但我无法在代码中得到任何东西。

在此处输入图像描述

我尝试过的:

TheSocket.java

public class TheSocket { public static String response = "hello"; public static String request; public static String webServerAddress; public static ServerSocket s; protected static ServerSocket getServerSocket(int port)throws Exception{ return new ServerSocket(port); } public static void handleRequest(Socket s){ BufferedReader is; PrintWriter os; try{ webServerAddress = s.getInetAddress().toString(); is = new BufferedReader(new InputStreamReader(s.getInputStream())); request = is.readLine(); System.out.println(request); os = new PrintWriter(s.getOutputStream(), true); os.println("HTTP/1.0 200"); os.println("Content-type: text/html"); os.println("Server-name: TheSocket"); os.println("Content-length: " + response.length()); os.println(""); os.println(response); os.flush(); os.close(); s.close(); }catch(Exception e){ System.out.println("Failed to send response to client: " + e.getMessage()); }finally{ if(s != null){ try{ s.close(); }catch(Exception e){ e.printStackTrace(); } } } return; } } 

Main.java

 public class Main { public static void main(String[] args)throws Exception{ TheSocket.s = TheSocket.getServerSocket(6789); while(true){ Socket serverSocket = TheSocket.s.accept(); TheSocket.handleRequest(serverSocket); } } 

PHP-CONNECT.php – 为了获取其他用户端口,我手动连接并使用网页上显示的端口。

  

上面代码的问题是,除非我向前移动,否则它无法进入套接字。

如果您有任何疑问,请评论!

我遇到了类似的问题。 并试图以类似的方式解决它。

你的代码的某些部分对我来说是错误的。 Java中的套接字是为TCP制作的,但标题是UDP 。 因此你应该使用DatagramSockets。 但是后来我们也陷入了困境。 HTTP请求也使用tcp,因此在关闭tcp会话后,使用HTTP打开端口可能会导致端口损坏。 (只是一个猜测)


 public class Main { public static void main(String[] args) { try { String httpRequest = "GET /index.php HTTP/1.1\n" + "Host: "; InetAddress IPAddress = InetAddress.getByName(); 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();} } } 

上面的代码理论上会发出HTTP over UDP请求。 这样显示的端口就是UDP端口。 在我的情况下,我没有从PHP服务器得到任何响应,并坚持在clientSocket.recieve(..)。 我想因为我的网络服务器的防火墙阻止了udp数据包。 如果代码适用于任何人,我会这样做:

  1. 将所有访问的ips和端口保存到数据库,并将它们列出到另一个客户端。
  2. 将上述DatagramPackets中的数据写入其他客户端。

我希望这可能有所帮助。 如果有人可以完全工作,我也会对它感兴趣:)