2016-08-04 101 views
1

解決方案

我嘗試了很多我在網上找到的東西。我試圖通過代碼綁定到0.0.0.0:如何接受到Java Web服務器的遠程連接

InetAddress addr = InetAddress.getByName("0.0.0.0"); 
ServerSocket socket = new ServerSocket(5000, 50, addr); 

哪家做工作。然後我嘗試了下面的代碼,其中DID最終工作。

InetAddress addr = InetAddress.getByAddress(new byte[] {0x00,0x00,0x00,0x00}); 
ServerSocket socket = new ServerSocket(5000, 50, addr); 

如果任何人都可以解釋爲什麼這工作,但另一個沒有,這將不勝感激。

主後

我目前正在接受來自我的遠程Amazon Web服務EC2服務器一個ServerSocket連接(Ubuntu的14.04,爪哇1.8.0_101)。

這裏是我與

public void CallbackListen() { 

    new Thread(new Runnable() { 
     public void run(){ 

      try{ 

      ServerSocket server = new ServerSocket(5000); 
       Socket conn = server.accept(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 

       OutputStream out = conn.getOutputStream(); 
       int count = 0; 

       while (true) 
       { 
       count++; 
       String line = reader.readLine(); 
       if (line == null) 
       { 
        System.out.println("Connection closed"); 
        break; 
       } 
       System.out.println("" + count + ": " + line); 
       if (line.equals("")) 
       { 
        System.out.println("Writing response..."); 

        // need to construct response bytes first 
        byte [] response = "<html><body>Hello World</body></html>".getBytes("ASCII"); 

        String statusLine = "HTTP/1.1 200 OK\r\n"; 
        out.write(statusLine.getBytes("ASCII")); 

        String contentLength = "Content-Length: " + response.length + "\r\n"; 
        out.write(contentLength.getBytes("ASCII")); 

        // signal end of headers 
        out.write("\r\n".getBytes("ASCII")); 

        // write actual response and flush 
        out.write(response); 
        out.flush();; 
       } 
       } 
      } 
      catch(Exception e){ 


      } 

     } 
    }).start(); 

的目的是爲了使用它作爲一個回調URL用於recieving數據POST請求使用的代碼。現在,它正在使用localhost:5000,但我無法遠程訪問它。我的服務器正在接受端口5000上的入站TCP請求。當我運行netstat -l命令時,而不是具有*:5000的本地地址,它是[::]:5000,而不是具有*:*的外地址,它是 [::]:*。

如何更改我的代碼以接受外部請求?

感謝,

-Justin

+1

您在安全組中有什麼規則?您是否在安全組中打開端口5000? – randominstanceOfLivingThing

+0

@randominstanceOfLivingThing,「我的服務器正在接受端口5000上的入站TCP請求。」 – Schwaitz

+0

@Schwaitz你的服務器正在接受什麼,通過'netstat'可見,以及被稱爲** Security Group **的AWS防火牆正在接受什麼,這兩件事情完全不同。因此,重申一下,您是否在分配給EC2實例的安全組中打開了5000端口? –

回答

0

我試了很多事情,我在網上找到。我試圖通過代碼綁定到0.0.0.0:

InetAddress addr = InetAddress.getByName("0.0.0.0"); 
ServerSocket socket = new ServerSocket(5000, 50, addr); 

哪家做工作。然後我嘗試了下面的代碼,其中DID最終工作。

InetAddress addr = InetAddress.getByAddress(new byte[] {0x00,0x00,0x00,0x00}); 
ServerSocket socket = new ServerSocket(5000, 50, addr);