This is an echo server that can handle multiple threads, but it doesn't work correctly. The problem is in the echo, only every other line is echoed back and forth and I am not sure why. Any suggestions? Thanks.
Code:
// Server that handles multiple threads.
import java.io.*;
import java.net.*;
public class Server {
static final int PORT = 10000;
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(PORT);
System.out.println("Server Started");
try {
while(true) {
// Blocks until a connection occurs:
Socket socket = s.accept();
try {
new ThreadServer(socket);
} catch(IOException e) {
// If it fails, close the socket, otherwise the thread will close it:
socket.close();
}
}
} finally {
s.close();
}
}
}
// Server uses multithreading to handle any number of clients.
import java.io.*;
import java.net.*;
class ThreadServer extends Thread {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ThreadServer(Socket s) throws IOException {
socket = s;
in =
new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
// Enable auto-flush:
out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())), true);
start(); // Calls run()
}
public void run() {
try {
while (true) {
String str = in.readLine();
if (str.equals("END")) break;
System.out.println("Echoing: " + str);
out.println(str);
}
System.out.println("closing...");
} catch (IOException e) {
} finally {
try {
socket.close();
} catch(IOException e) {}
}
}
}
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
InetAddress ip = InetAddress.getByName("localhost");
System.out.println("addr = " + ip);
Socket socket = new Socket(ip, 10000);
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(
System.in));
// Output is automatically flushed by PrintWriter:
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())),true);
String userInput;
while ((userInput = in.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
}
} finally {
System.out.println("closing...");
socket.close();
}
}
}