Yurii Vasylkiv
Yurii Vasylkiv

Reputation: 1

Creating server in Java for global access

I have a problem which i've already been struggling for 3 days. I need to create server based on socket connection beetween the different local networks.

I found a lot of examples like this :

import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

/**
 * Created by yar 09.09.2009
 */
public class HttpServer {

    public static void main(String[] args) throws Throwable {
        ServerSocket ss = new ServerSocket(9999);
        while (true) {
            Socket s = ss.accept();
            System.err.println("Client accepted");
            new Thread(new SocketProcessor(s)).start();
        }
    }

    private static class SocketProcessor implements Runnable {

        private Socket s;
        private InputStream is;
        private OutputStream os;

        private SocketProcessor(Socket s) throws Throwable {
            this.s = s;
            this.is = s.getInputStream();
            this.os = s.getOutputStream();
        }

        public void run() {
            try {
                readInputHeaders();
                writeResponse("<html><body><h1>Hello from Habrahabr</h1></body></html>");
            } catch (Throwable t) {
                /*do nothing*/
            } finally {
                try {
                    s.close();
                } catch (Throwable t) {
                    /*do nothing*/
                }
            }
            System.err.println("Client processing finished");
        }

        private void writeResponse(String s) throws Throwable {
            String response = "HTTP/1.1 200 OK\r\n" +
                    "Server: YarServer/2009-09-09\r\n" +
                    "Content-Type: text/html\r\n" +
                    "Content-Length: " + s.length() + "\r\n" +
                    "Connection: close\r\n\r\n";
            String result = response + s;
            os.write(result.getBytes());
            os.flush();
        }

        private void readInputHeaders() throws Throwable {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            while(true) {
                String s = br.readLine();
                if(s == null || s.trim().length() == 0) {
                    break;
                }
            }
        }
    }
}

But problem is : i can access to this ip:port only from the same local network. If i trying to connect from the same network (from Android smartphone to local computer which has the same network ip)? so in this case all is successful, but if i trying to run the same Server sample code on, say for example AWS (Amazon Web Server) it doesn't work :(

-> Couldn't get I/O for the connection to 172.31.23.98 (java)

or

-> org.apache.http.conn.ConnectTimeoutException: Connect to 172.31.23.98:9999 timed out (groovy)

i'm using this sample code of Server :

  public static void main(String[] args) throws IOException {
        int portNumber = 9998;
        BufferedOutputStream bos = null;

        while (true) {

            try (ServerSocket serverSocket = new ServerSocket(portNumber);
                 Socket clientSocket = serverSocket.accept();
                 PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                 InputStream in = clientSocket.getInputStream();
                 BufferedReader inWrapper = new BufferedReader(new InputStreamReader(in))) {
                FileOutputStream fos = new FileOutputStream(new File("D:/BufferedAudio.wav"));
                bos = new BufferedOutputStream(fos);
                System.out.println("Connected with client");


                String inputLine, outputLine;
                int bytesRead;
                byte[] buffer = new byte[1024 * 1024];

                while ((bytesRead = in.read(buffer)) > 0) {
                    bos.write(buffer, 0, bytesRead);
                    System.out.println(new String(buffer, Charset.defaultCharset()));
                    bos.flush();
                    out.println("Hello!!! I'm server");
                }
                bos.close();

            } catch (IOException e) {

                System.out.println("Exception caught when trying to listen on port "
                        + portNumber + " or listening for a connection");
                System.out.println(e.getMessage());
                throw e;

            }

            System.out.println("Upps, the loop was unexpectedly out");

        }
    }

Here's the code of client :

 public static void main(String[] args) throws IOException {


        String IP = "172.31.23.98";
        int port = 9998;

        try (
                Socket connectionSocket = new Socket(IP, port);
                PrintWriter out = new PrintWriter(connectionSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(connectionSocket.getInputStream()))
        ) {
            BufferedReader stdIn =
                    new BufferedReader(new InputStreamReader(System.in));
            String fromServer;
            String fromUser;

            while ((fromServer = in.readLine()) != null) {
                System.out.println("Server: " + fromServer);

                fromUser = stdIn.readLine();
                if (fromUser != null) {
                    System.out.println("Client: " + fromUser);
                    out.println(fromUser);
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + IP);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                    IP);
            System.exit(1);
        }
    }

These are the samples from the internet.

Amm how can i modify this code to access from Client to Server from different networks ?

Upvotes: 0

Views: 829

Answers (1)

Philipp
Philipp

Reputation: 69703

The IP range 172.16.0.0 to 172.31.255.255 is a private address space for use in local area networks. IPs from that range are only valid in the same private LAN.

When you deploy your server software on a host on the Internet which is outside of your local area network, you need to replace it with the IP address of that host. I never used AWS, but the first place I would be looking for when I would want to know the public IP address of a server I rent, would be the web-based control panel. When you have shell access to the server, you can also find it out with ipconfig on Windows and ifconfig on Unix.

Upvotes: 1

Related Questions