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.

Silver Archer
  • 167
  • 3
  • 3
  • 14
  • 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. – 3kings Nov 01 '16 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? – Hovercraft Full Of Eels Nov 01 '16 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 – Md Ayub Ali Sarker Nov 01 '16 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 – Silver Archer Nov 02 '16 at 04: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. – user207421 Nov 02 '16 at 05:43
  • @EJP I think maybe its the started server problem, how can I do that ? – Silver Archer Nov 02 '16 at 05:45
  • Start the server the same way you started the client, only first, and with its own class name instead of the client's. This is really rather elementary. – user207421 Nov 02 '16 at 05:47
  • @EJP Oh Yes! i got it! Oh My God thank you so much !! – Silver Archer Nov 02 '16 at 05:51
  • How exactly did you expect your client to connect to a server that wasn't executing? – user207421 Nov 02 '16 at 06:22
  • You might want to see this answer:> http://stackoverflow.com/questions/6865538/solving-a-communications-link-failure-with-jdbc-and-mysql – Marco Schoolenberg Mar 20 '17 at 23:31

1 Answers1

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!
Nicolas Filotto
  • 43,537
  • 11
  • 94
  • 122