Last active
July 26, 2018 15:53
-
-
Save Thomascountz/ad5a87e9cfd7588411d0420b22dcfd44 to your computer and use it in GitHub Desktop.
Threaded Echoing Server in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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