4

I recently learn about Socket Programming between client and server. So I thought of doing an exercise of connecting both client and server. However, I have encountered this error message when I try to run the code: Exception in thread "main" java.net.ConnectException: Connection refused: connect

This is my client class code:

public class clientpart {
    public static void main(String[]args) throws UnknownHostException, IOException {
        Scanner input = new Scanner(System.in);
        int port = 8080;
        String host=null;
        String answer; String sendMessage; String receivedMessage;
        InetAddress address = InetAddress.getByName(host);
        Socket socket= new Socket(address,port);

        OutputStream os = socket.getOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(os);
        BufferedWriter bw = new BufferedWriter(osw);

        System.out.println("Please answered the following question: ");
        System.out.println("What is the subject code for Socket Programming?");
        answer = input.nextLine();

        sendMessage = answer;
        bw.write(sendMessage);
        bw.newLine();
        bw.flush();
        System.out.println("Message sent to server: "+sendMessage);

        InputStream is = socket.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        receivedMessage = br.readLine();
        System.out.println("Message received from server : " + receivedMessage);
    }
}

This is my server code:

public class serverpart {
    public static Socket socket;
    public static void main(String[]args) throws IOException {
        int port = 8080;
        String answer; String returnedMessage; String reply;
        ServerSocket server = new ServerSocket(port);
        System.out.println("Server start at port "+port+".");

        while(true)
        {
            socket = server.accept();
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            answer = br.readLine();
            System.out.println("Message sent from client: " + answer);

            if("NET 3202".equals(answer) || "net 3202".equals(answer) || "NET3202".equals(answer) || "net3202".equals(answer)){
                reply = "Correct!";
                returnedMessage = reply;
            }
            else{
                reply = "Wrong!";
                returnedMessage = reply;
            }

            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(returnedMessage);
            bw.newLine();
            System.out.println("Message replied to client: "+returnedMessage);
            bw.flush();
        }
    }
}

The full error message is:

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 clientpart.main(clientpart.java:13)
C:\Users\PeiErn\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

I hope someone can help me, thanks.

10
  • I would probably make the Input / Output Streams at the same time right after you accept the connection (on the server) and right after you connected (on the client). I believe it is going through and since they are running on different "threads" the streams aren't getting created at the same time. which could cause an error? idk? just my opinion. Commented Nov 1, 2016 at 14:18
  • 1
    Thank you @nicolas for formatting the poster's code. Original poster: posting poorly formatted code only makes your question harder to read and understand -- why do this? Commented Nov 1, 2016 at 14:19
  • Only the problem is your port number. you can not use reserved port. just change the port number to some thing like 9085 it will work Commented Nov 1, 2016 at 14:23
  • @MdAyubAliSarker I have tried to change port number to others other than 80, but then the client class shows me this error: Exception in thread "main" java.net.ConnectException: Connection refused: connect Commented Nov 2, 2016 at 4:45
  • 'ConnectException: connection refused' just means you got the hostname or IP address or port wrong in the client, or you hadn't started the server when you ran the client. Commented Nov 2, 2016 at 5:43

1 Answer 1

7

There are 2 issues in your program:

  1. You use the port 80 which is part of the well-known ports or system ports (0 to 1023), so you need to launch your server with the admin rights or change it for 8080 for example.
  2. You forgot to call bw.newLine() after each bw.write(sendMessage) such that it waits for ever since on the other side you call br.readLine() which means that it waits for an entire line while you don't send the end of line characters.

Change your code for this:

Server part:

public class serverpart {
    public static Socket socket;
    public static void main(String[]args) throws IOException {
        int port = 8080;
        ...
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(returnedMessage);
            bw.newLine();
            ...

Output:

Server start at port 8080.
Accepted
Message sent from client: net3202
Message replied to client: Correct!

Client part:

public class clientpart {
    public static void main(String[]args) throws IOException {
        Scanner input = new Scanner(System.in);
        int port = 8080;
        ...
        bw.write(sendMessage);
        bw.newLine();
        bw.flush();
        ...

Output:

Please answered the following question: 
What is the subject code for Socket Programming?
net3202
Message sent to server: net3202
Message received from server : Correct!
Sign up to request clarification or add additional context in comments.

5 Comments

When I change the port to 8080, it gave me this error message: Exception in thread "main" java.net.ConnectException: Connection refused: connect
Also I check if the server are listening on port 8080, and its not. Is that the problem? Thanks.
did you change it on both the client and the server? do you launch both on the same machine? yes that's right, connection refused means that the server is not listening or the firewall blocks requests on this port
Apparently I have to start the server first oh my god thank you so much for the help!
yes indeed you always have to start the server first

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.