Skip to content

Instantly share code, notes, and snippets.

@Thomascountz
Last active July 26, 2018 15:53
Show Gist options
  • Save Thomascountz/ad5a87e9cfd7588411d0420b22dcfd44 to your computer and use it in GitHub Desktop.
Save Thomascountz/ad5a87e9cfd7588411d0420b22dcfd44 to your computer and use it in GitHub Desktop.
Threaded Echoing Server in Java
import java.io.*;
import java.net.*;
public class ClientWorker implements Runnable {
private Socket clientSocket;
ClientWorker(Socket clientSocket){
this.clientSocket = clientSocket;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(this.clientSocket.getOutputStream(), true);
while (true) {
String line = in.readLine();
out.println(line);
}
} catch (IOException e) {
System.out.println("Something went wrong.");
System.exit(-1);
}
}
}
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
int port = 5000;
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Listening on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
ClientWorker clientWorker = new ClientWorker(clientSocket);
Thread thread = new Thread(clientWorker);
thread.start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment