Como aceitar ligações remotas a um servidor Web Java
Solução
Tentei muitas coisas que encontrei online. Tentei ligar-me a 0.0.0.0 através do Código:InetAddress addr = InetAddress.getByName("0.0.0.0");
ServerSocket socket = new ServerSocket(5000, 50, addr);
que não funcionou . Então eu tentei o seguinte código que Fez acabar trabalhando.
InetAddress addr = InetAddress.getByAddress(new byte[] {0x00,0x00,0x00,0x00});
ServerSocket socket = new ServerSocket(5000, 50, addr);
Se alguém puder explicar porque é que isto funciona, mas o outro não, seria muito apreciado.
principal Posto
Estou a tentar aceitar ligações a um servidor do meu servidor EC2 da Amazon. (Ubuntu 14.04, Java 1.8.0_101). Aqui está o código com o qual estou a trabalhar.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();
o propósito é usá-lo como uma url de retorno para receber pedidos de POST com dados. Neste momento, está a funcionar em localhost:5000, mas não consigo aceder remotamente. O meu servidor está a aceitar pedidos TCP na porta 5000. Quando executo um comando netstat -l
, em vez de ter um endereço Local de *:5000, é [::]:5000, e em vez de ter um endereço Estrangeiro de*:*, é [::]:*.
1
1 answers
Tentei muitas coisas que encontrei online. Tentei ligar-me a 0.0.0.0 através do Código:
InetAddress addr = InetAddress.getByName("0.0.0.0");
ServerSocket socket = new ServerSocket(5000, 50, addr);
Que não funcionou . Então eu tentei o seguinte código que fez acabar trabalhando.
InetAddress addr = InetAddress.getByAddress(new byte[] {0x00,0x00,0x00,0x00});
ServerSocket socket = new ServerSocket(5000, 50, addr);
0
Author: Schwaitz, 2016-08-07 02:31:42