Exception in thread “main” java.net.ConnectException: Connection refused: connect Socket Programming Java

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!

Leave a Comment