使用Java创建服务器以进行全局访问

时间:2015-10-20 08:01:43

标签: java sockets

我有一个问题,我已经挣扎了3天。我需要根据不同本地网络之间的套接字连接创建服务器。

我发现了很多像这样的例子:

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

但问题是: 我只能从同一个本地网络访问此ip:端口。如果我尝试从同一个网络连接(从Android智能手机到具有相同网络IP的本地计算机)?所以在这种情况下一切都很成功,但如果我试图运行相同的服务器示例代码,比如说AWS(亚马逊网络服务器) 它没有用:(

- &GT;无法获得与172.31.23.98(java)

的连接的I / O.

- &GT; org.apache.http.conn.ConnectTimeoutException:连接到172.31.23.98:9999超时(groovy)

我正在使用服务器的示例代码:

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

        }
    }

这是客户代码:

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

这些是来自互联网的样本。

Amm如何修改此代码以从不同网络从客户端访问服务器?

1 个答案:

答案 0 :(得分:1)

IP范围172.16.0.0至172.31.255.255 is a private address space for use in local area networks。该范围内的IP仅在同一专用LAN中有效。

在局域网之外的Internet上的主机上部署服务器软件时,需要将其替换为该主机的IP地址。我从来没有使用过AWS,但是当我想知道我租用的服务器的公共IP地址时,我想要的第一个地方就是基于网络的控制面板。当您具有对服务器的shell访问权限时,您也可以在Windows上使用ipconfig和在Unix上使用ifconfig找到它。