[英]Java-Client PHP-Server UDP Hole Punching example code
我正在开发一个需要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 - 为了获取其他用户端口,我手动连接并使用网页上显示的端口。
<?php
echo $_SERVER['REMOTE_ADDR'].':'.$_SERVER['REMOTE_PORT'];
?>
上面代码的问题是,除非我向前移动,否则它无法进入套接字。
如果您有任何疑问,请评论!
我遇到了类似的问题。 并试图以类似的方式解决它。
你的代码的某些部分对我来说是错误的。 Java中的套接字是为TCP制作的,但标题是UDP 。 因此你应该使用DatagramSockets。 但是后来我们也陷入了困境。 HTTP-Requests也使用tcp,因此在关闭tcp会话后,使用HTTP打开端口可能会导致端口损坏。 (只是一个猜测)
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();}
}
}
上面的代码理论上是通过UDP请求发送HTTP。 这样显示的端口就是UDP端口。 在我的情况下,我没有从PHP服务器得到任何响应,并坚持在clientSocket.recieve(..)。 我想因为我的网络服务器的防火墙阻止了udp数据包。 如果代码适用于任何人,我会这样做:
我希望这可能有所帮助。 如果有人可以完全工作,我也会对它感兴趣:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.