如何接受到Java Web服务器的远程连接

如何接受到Java Web服务器的远程连接

问题描述:

解决方案

我尝试了很多我在网上找到的东西。我试图通过代码绑定到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:

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