[英]Java TCP Socket Programming: Can not connect to remote host
我有一個Java程序,它接受來自Web瀏覽器的http請求,並且作為響應,程序發送文本文件內容以在Web瀏覽器中顯示。 當我從運行Java代碼的同一台計算機上安裝的瀏覽器發出請求時,該程序運行正常,但是當我從與運行Java代碼的不同計算機上的其他Web瀏覽器發出請求時,該程序沒有收到任何請求。
這是我從網絡瀏覽器發出請求的方式:-
http://localhost:port_number/
This is working fine...
這是我從不在計算機上的其他Web瀏覽器發出請求的方式:
http://my_ip_address:port_number/
This is not working...
這是我的Java代碼:-
while (true) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
try {
serverSocket = new ServerSocket(32768);
clientSocket = serverSocket.accept();
InetAddress ia = clientSocket.getInetAddress();
jTextArea1.append("Connected to : " + ia + "\n");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine, outputLine;
String s = (String) JOptionPane.showInputDialog(this, "Enter File Name : ");
File f = new File(s);
if (f.exists()) {
out.println("http/1.1 200 ok\r");
out.println("Mime version 1.1");
out.println("Content-Type: text/html\r");
out.println("Content-Length: " + f.length() + "\r");
out.println("\r");
BufferedReader d = new BufferedReader(new FileReader(s));
String line = " ", a;
while ((a = d.readLine()) != null) {
line = line + a;
}
out.write(line);
out.flush();
jTextArea1.append("File Delivered.\n");
d.close();
}
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
jTextArea1.append("Accept failed.");
System.exit(1);
}
}
這與您編寫的代碼無關。 您需要使您的IP地址可公開訪問。 這是一個相關的主題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.