如何让我的客户端与我的服务器通信?

时间:2015-03-08 18:05:53

标签: java sockets client server

我有一个客户端和服务器程序。当我在localhost上同时运行它时,它可以工作,但现在我已将服务器程序移动到托管在数字海洋上的服务器上。当我在笔记本电脑上执行客户端程序时,我希望我的客户端和服务器进行通信。

这是客户端代码

public class ClientExample{
    Socket requestSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    ClientExample(){}
    void run()
    {
        try{
            //1. creating a socket to connect to the server
            requestSocket = new Socket("182.15.6.1", 2222); //ip is example
            System.out.println("Connected to localhost in port 2004");
            //2. get Input and Output streams
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());
            //3: Communicating with the server
            do{
                try{
                    message = (String)in.readObject();
                    System.out.println("server>" + message);
                    sendMessage("hello!");
                    sendMessage("How are you");
                    message = "bye";
                    sendMessage(message);
                }
                catch(ClassNotFoundException classNot){
                    System.err.println("data received in unknown format");
                }
            }while(!message.equals("bye"));
        }
        catch(UnknownHostException unknownHost){
            System.err.println("You are trying to connect to an unknown host!");
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
        finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                requestSocket.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
    void sendMessage(String msg)
    {
        try{
            out.writeObject(msg);
            out.flush();
            System.out.println("client>" + msg);
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
    public static void main(String args[])
    {
        ClientExample client = new ClientExample();
        client.run();
    }
}

这是我的服务器代码

public class ExampleServer{
    ServerSocket providerSocket;
    Socket connection = null;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    ExampleServer(){}
    void run()
    {
        try{
            //1. creating a server socket
            providerSocket = new ServerSocket(2222, 10);
            //2. Wait for connection
            System.out.println("Waiting for connection");
            connection = providerSocket.accept();
            System.out.println("Connection received from " + connection.getInetAddress().getHostName());
            //3. get Input and Output streams
            out = new ObjectOutputStream(connection.getOutputStream());
            out.flush();
            in = new ObjectInputStream(connection.getInputStream());
            sendMessage("Connection successful");
            //4. The two parts communicate via the input and output streams
            do{
                try{
                    message = (String)in.readObject();

                    System.out.println("client>" + message);
                    if (message.equals("bye"))
                        sendMessage("bye");
                }
                catch(ClassNotFoundException classnot){
                    System.err.println("Data received in unknown format");
                }
            }while(!message.equals("bye"));
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
        finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                providerSocket.close();
            }
            catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
    void sendMessage(String msg)
    {
        try{
            out.writeObject(msg);
            out.flush();
            System.out.println("server>" + msg);
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
    public static void main(String args[])
    {
        ExampleServer server = new ExampleServer();
        while(true){
            server.run();
        }
    }
}

我得到的错误是:

java.net.ConnectException: Connection timed out: connect
        at java.net.DualStackPlainSocketImpl.connect0(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
        at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
        at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
        at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
        at java.net.PlainSocketImpl.connect(Unknown Source)
        at java.net.SocksSocketImpl.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at java.net.Socket.<init>(Unknown Source)
        at java.net.Socket.<init>(Unknown Source)
        at ClientExample.run(ClientExample.java:13)
        at ClientExample.main(ClientExample.java:66)
Exception in thread "main" java.lang.NullPointerException
        at ClientExample.run(ClientExample.java:43)
        at ClientExample.main(ClientExample.java:66)

我被要求ping服务器,这就是结果,好像对我来说。

 Pinging MyServer with 32 bytes of data:
Reply from MyServer: bytes=32 time=151ms TTL=50
Reply from MyServer: bytes=32 time=116ms TTL=50
Reply from MyServer: bytes=32 time=101ms TTL=50
Reply from MyServer: bytes=32 time=98ms TTL=50

Ping statistics for MyServer:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% los
Approximate round trip times in milli-seconds:
    Minimum = 98ms, Maximum = 151ms, Average = 116ms

1 个答案:

答案 0 :(得分:2)

您的服务器正在端口 2004

上运行
providerSocket = new ServerSocket(2004, 10);
                                   /\
                                   ||

并且您的客户要求在不同端口 2222

上建立连接
requestSocket = new Socket("182.15.6.1", 2222); //ip is example
                                          /\
                                          ||

和Exception将在最后一行阻止

in.close(); // As connection not made so `in` still isn't innitialized