Fail to read/write data to socket when trying to run echo server. No exception thrown and there is no response to console input. What’s not correct in code?
public class Server {
static ServerSocket server;
public static void main(String[] args) throws IOException {
String hostname = "127.0.0.1";
try{
server = new ServerSocket(8888);
} catch (IOException e) {
System.out.println("Could not listen on port 8888");
System.exit(-1);
}
Socket theSocket = null;
try {
theSocket = new Socket(hostname, 8888);
BufferedReader networkIn = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(theSocket.getOutputStream(), true);
System.out.println("Connected to echo server");
while (true) {
String theLine = userIn.readLine();
if (theLine.equals("."))
break;
out.println(theLine);
out.flush();
System.out.println("networkIn: "+networkIn.readLine());
}
networkIn.close();
out.close();
System.out.println("out.close();");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You created two unrelated sockets, one for accepting connections, and one for connecting to (hostname,8888). You need to call
accept()on the server socket to actually get clients connected. See the tutorial.