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.