1

I am new to socket programming and just trying my hands on a small program to get a hold of how sockets work. There's a client and a server, and I am just trying to load some strings from server and display. But every time I make a server Socket, I get java.net.BindException, even though I manually clean up all resources in finally block. Have a look at below code and please suggest some edits on what could cause this problem. I am using Eclipse.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class AdviceServer {

String[] adviceList = {
        "Take smaller bites",
        "Go for the tight jeans. No they do NOT" + "make you look fat.",
        "One word: inappropriate",
        "Just for today, be honest. Tell your"
                + "boss what you *really* think",
        "You might want to rethink that haircut." };

public void setUpServer() {

    ServerSocket serverSocket = null;

    try {
        if (serverSocket == null)
        serverSocket = new ServerSocket(8003);
        int i = 2;

        // Keep looping till we have clients.
        while (true) {
            Socket sock = serverSocket.accept();
            PrintWriter pw = new PrintWriter(sock.getOutputStream());
            pw.write(getRandomAdvice());
            pw.close();
            System.out.println(getRandomAdvice());
        }

     //   serverSocket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

public void setUpClient() {

    // Make a socket
    Socket chatSocket = null;
    try {
        chatSocket = new Socket("127.0.0.1", 8003);
        InputStreamReader isr = new InputStreamReader(
                chatSocket.getInputStream());

        // Make a chain stream Buffered Reader
        BufferedReader br = new BufferedReader(isr);

        String text;
        while ((text = br.readLine()) != null) {
            System.out.println(text);
        }

        br.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (chatSocket != null) {
            try {
                chatSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


}

public String getRandomAdvice() {
    return adviceList[(int) (Math.random() * adviceList.length)];

}

public static void main(String[] args) {
    AdviceServer as = new AdviceServer();

    as.setUpClient();
    as.setUpServer();
}
}

Any help would be greatly appreciated, as I have tried almost everything to rectify this.

2
  • Have you tried a different port other than 8003? Commented Nov 8, 2014 at 9:07
  • Yeah, I have tried different ports, other than this too, 5000, 6000, 8002, etc.. But I get the same exception every time. What are you getting when you run this on Eclipse? Commented Nov 8, 2014 at 9:09

3 Answers 3

1

You must be running your code twice,and hence getting BindException.As in the first run the server would run and listen on port 8003 ,and you will get ConnectionRefused error.The next time you run this program ,client side would get the message from the server followed by BindException as you are running server code again.

The problem is that the server and client are running on same main thread. Try running server in different thread. And also run server first at it would be listening to the client for connections.

Sign up to request clarification or add additional context in comments.

7 Comments

Why would he get ConnectionRefused error? not that that even exists. It is ConnectException: connection refused actually. He didn't mention any such thing.
Thanks Rashmi, the problem was with blocking of main thread which none other answers had commented. But if I launch it in a separate thread, it works fine, so I'm going to mark this as accepted answer.
@guaravjain Blocking of the main thread has nothing to do with the BindException. It will certainly impede further progress of your program once you're past that point, but that's not what your stated question was about.
@EJP Yes you are right its ConnectException:connection refused.This exception usually occurs when there is no service listening on the port you are trying to connect to.As in his code he is starting client first ,this would occur
@EJP it certainly does. I was forced to run the code twice as the first time main thread was blocked by accept method. If i run it in a separate thread I don't need to run it twice and hence there is no BindException.
|
1

Something else is already listening at port 8003. Possibly a prior instance of your program, possibly something else. Use netstat to find out which.

If it's your own program, change the ServerSocket creation to this:

serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(8003));

Comments

0

The problem is you are initializing the client first and then server.

as.setUpClient();

as.setUpServer();

And what I believe you are doing it to have the code run twice. First you get Connection refused and when u run it the second time you get BindException. Without closing the previous console.

Also check if any other process is binding on the same port. If you are on windows run

nestat -ano

If you see port 8003 refer that pid and kill it using task manager.

Since you have already tried other ports I guess your problem is as stated first point.

Even if you were to reverse it the order in your code

as.setUpServer();

as.setUpClient();

And since your Socket sock = serverSocket.accept(); is blocking api. Your client code i.e as.setUpClient(); will not be called.

Split it as two file client and server. Run the server first then client. It will work.

Do some thing like this:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class AdviceServer {

    String[] adviceList = {
            "Take smaller bites",
            "Go for the tight jeans. No they do NOT" + "make you look fat.",
            "One word: inappropriate",
            "Just for today, be honest. Tell your"
                    + "boss what you *really* think",
            "You might want to rethink that haircut." };

    public void setUpServer() {

        ServerSocket serverSocket = null;

        try {
            if (serverSocket == null)
                serverSocket = new ServerSocket(8003);
            int i = 2;

            // Keep looping till we have clients.
            while (true) {
                Socket sock = serverSocket.accept();
                PrintWriter pw = new PrintWriter(sock.getOutputStream());
                pw.write(getRandomAdvice());
                pw.close();
                System.out.println(getRandomAdvice());
            }

            // serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public String getRandomAdvice() {
        return adviceList[(int) (Math.random() * adviceList.length)];

    }

    public static void main(String[] args) {
        AdviceServer as = new AdviceServer();

        as.setUpServer();

    }
}





import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

public class AdviceClient {

    public void setUpClient() {

        // Make a socket
        Socket chatSocket = null;
        try {
            chatSocket = new Socket("127.0.0.1", 8003);
            InputStreamReader isr = new InputStreamReader(
                    chatSocket.getInputStream());

            // Make a chain stream Buffered Reader
            BufferedReader br = new BufferedReader(isr);

            String text;
            while ((text = br.readLine()) != null) {
                System.out.println(text);
            }

            br.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (chatSocket != null) {
                try {
                    chatSocket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


    }

    public static void main(String[] args){

        AdviceClient client = new AdviceClient();
        client.setUpClient();
    }
}

10 Comments

That would, cause a ConnectException. He is getting a BindException.
Reason he is getting that is because he would have run the code once. Since the client will throw ConnectExcepiton and he would have run it again and get a bind exception. I think you should reconsider the downvote ;)
You should reconsider your answer. He didn't mention getting a ConnectException, and getting a ConnectException won't cause a subsequent BindException.
let him comment as to if has worked I'll take it back. Gaurav please restart u r eclipse and let us know the results.
In other words you're just guessing.
|

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.