简体   繁体   中英

Client socket connection refused

I am trying to understand how sockets work in Java, thus I wanted to take a look at a client-server implementation. I found this: Creating a Simple Java TCP/IP Server and Client Socket .

The server seems to work properly if I pass localhost or 127.0.0.1 however the client will refuse to connect on either one of those, throwing a connection refused exception, although I started the server before the client.

Server output:

Running Server: Host=127.0.0.1 Port=5069

Client output:

Exception in thread "main" java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at java.net.Socket.<init>(Socket.java:434)
    at java.net.Socket.<init>(Socket.java:244)
    at Client.<init>(Client.java:12)
    at Client.main(Client.java:29)

My Java code:

public class Server {
    private ServerSocket server;

    public Server(String ipAddress) throws Exception {
        if (ipAddress != null && !ipAddress.isEmpty()) {
//            System.out.println(InetAddress.getByName(ipAddress));
            this.server = new ServerSocket(0, 1, InetAddress.getByName(ipAddress));
        } else {
            this.server = new ServerSocket(0, 1, InetAddress.getLocalHost());
        }
    }

    private void listen() throws Exception {
        String data = null;
        Socket client = this.server.accept();
        String clientAddress = client.getInetAddress().getHostAddress();
        System.out.println("\r\nNew connection from " + clientAddress);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(client.getInputStream()));
        while ((data = in.readLine()) != null) {
            System.out.println("\r\nMessage from " + clientAddress + ": " + data);
        }
    }

    public InetAddress getSocketAddress() {
        return this.server.getInetAddress();
    }

    public int getPort() {
        return this.server.getLocalPort();
    }

    public static void main(String[] args) throws Exception {
        Server app = new Server("localhost");
        System.out.println("\r\nRunning Server: " +
                                   "Host=" + app.getSocketAddress().getHostAddress() +
                                   " Port=" + 50696);

        app.listen();
    }

}

public class Client {
    private Socket socket;
    private Scanner scanner;

    private Client(InetAddress serverAddress, int serverPort) throws Exception {
        this.socket = new Socket(serverAddress, serverPort);
        this.scanner = new Scanner(System.in);
    }

    private void start() throws IOException {
        String input;
        while (true) {
            input = scanner.nextLine();
            PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
            out.println(input);
            out.flush();
        }
    }

    public static void main(String[] args) throws Exception {
//        System.out.println( InetAddress.getByName("localhost"));
        Client client = new Client(
                InetAddress.getByName("127.0.0.1"), 50696);

        System.out.println("\r\nConnected to Server: " + client.socket.getInetAddress());
        client.start();
    }
}

If you are trying to connect to the wrong port, then the connection will be refused (see this answer ). Your server is not listening on the port 5069 . You obviously set it to listen on port 0 right here:

if (ipAddress != null && !ipAddress.isEmpty()) {
    this.server = new ServerSocket(0, 1, InetAddress.getByName(ipAddress));
} else {
    this.server = new ServerSocket(0, 1, InetAddress.getLocalHost());
}

Look at the Javadoc for that constructor you used:

 public ServerSocket(int port, int backlog, InetAddress bindAddr) throws IOException 

Parameters:

port - the port number, or 0 to use a port number that is automatically allocated.

backlog - requested maximum length of the queue of incoming connections.

bindAddr - the local InetAddress the server will bind to

That first parameter is the port number, and you pass 0 for both constructors.

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