It's a bit hard to tell since you haven't included the exception message, and also not told if it's the client or server that's failing.
However something like this should work for you (this works for me);
Add two files to your eclipse project (in this example they're called
Server and
Client but you can call them whatever):
Server.java
package com.bornander.clientservertest;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class Server {
private final static Random random = new Random();
private final static String[] ADVICE_LIST = {
"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 yourboss what you *really* think",
"You might want to rethink that haircut."
};
private void go() throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
while(!serverSocket.isClosed()) {
Socket socket = serverSocket.accept();
PrintWriter writer = new PrintWriter(socket.getOutputStream());
String advice = getAdvice();
System.out.println("Sending advice: " + advice);
writer.write(advice);
writer.close();
System.out.println("Advice sent!");
socket.close();
}
}
private static String getAdvice() {
return ADVICE_LIST[random.nextInt() % ADVICE_LIST.length];
}
public static void main(String[] args) throws IOException {
Server server = new Server();
server.go();
}
}
Client.java
package com.bornander.clientservertest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client {
public void go() throws IOException {
System.out.println("Getting some good advice...");
Socket socket = new Socket("localhost", 8080);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String advice = reader.readLine();
System.out.println(advice);
reader.close();
socket.close();
}
public static void main(String[] args) throws IOException {
Client client = new Client();
client.go();
}
}
Then in
Eclipse, right click
Server.java and select
Debug as Java Application, and then right clock
Client.java and select
Debug as Java Application, in the
Console tab you should see the client getting some good advice.
Hope this helps,
Fredrik