简体   繁体   中英

Java TCP Socket Programming: Can not connect to remote host

I have a java program which accepts a http request from web browser and in response, program sends a text file contents to display in web browser. The program is working fine when I make request from browser which is installed on the same machine in which java code is running but when I make request from some other web browser which is not on the same machine as in which java code running, the program does not get any request.

This is how I make request from my web browser:-

http://localhost:port_number/   
This is working fine...

This is how I make request from some other web browser which is not on my machine:

http://my_ip_address:port_number/
This is not working...

And this is my java code:-

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

This is not related to the code that you've written. You need to make your IP address publicly accessible. Here's is a related thread.

  1. Check that you are indeed listening on 0.0.0.0:32768 and not 127.0.0.1:32768 or any other particulat IP (specially if you are connected to several network). Start a shell and use netstat -ano on Windows and netstat -anp on Unix or Mac.
  2. Check that your firewall allows remote connection to the port 32768

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM