好吧,这是我的代码:
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TcpServerEcho {
public static void main(String argv[]) {
int port = Integer.parseInt(argv[0]);
ServerSocket server_socket = null;
try {
InetAddress thisIp = InetAddress.getByName("kiravaio.homepc.it");
System.out.println(thisIp.getHostAddress());
//or
//server_socket = new ServerSocket(port, 10, InetAddress.getByName("79.47.49.68"));
server_socket = new ServerSocket(port, 10, thisIp);
}
catch (Exception e) {
System.err.println("Impossible to create socket server!");
System.out.flush();
System.exit(1);
}
System.out.printf("Server active on port: %d and on address %s\n", port, server_socket.getInetAddress());
Socket client_socket = null;
boolean exec = true;
while(exec) {
try {
client_socket = server_socket.accept();
InputStream is = client_socket.getInputStream();
OutputStream os = client_socket.getOutputStream();
boolean stop = false;
System.out.println("Received: ");
while(!stop) {
int b = is.read();
System.out.print((char)b);
if(b == -1) {stop = true;}
else {os.write( (byte)b );}
}
}
catch (IOException ioe) {
System.err.println("Error I/O!");
} finally {
try {
client_socket.close();
}
catch (IOException ioe) {}
}
System.out.println("");
}
try {
/* Never executed */
server_socket.close();
} catch (IOException ioe) {}
}
}
我无法在我的公共 IP 上创建一个套接字。我有一个域 kiravaio.homepc.it 每次我的 ip public 更改时都会更新。首先,我使用 InetAddress thisIp = InetAddress.getByName("kiravaio.homepc.it"); 获取我的 IP 地址 然后我创建套接字: server_socket = new ServerSocket(port, 10, thisIp); 但它总是失败,我不知道为什么,只有在 127.0.0.1 上创建一个套接字才有效!:(