我尝试过很多在网上找到的东西。我试图通过代码绑定到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);
如果有人能解释为什么这样有效,但另一个没有,那将非常感激。
我目前正在尝试从远程Amazon Web Services EC2服务器(Ubuntu 14.04,Java 1.8.0_101)接受与ServerSocket的连接。
以下是我正在使用的代码
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以接收带有数据的POST请求。现在,它正在使用localhost:5000,但我无法远程访问它。我的服务器正在接受端口5000上的入站TCP请求。当我运行netstat -l
命令时,而不是具有*:5000的本地地址,它是[::]:5000,而不是具有外部地址*:*,它是[::]:*。
如何更改我的代码以接受外来请求?
谢谢,
-Justin
答案 0 :(得分: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);