[英]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.