Skip to content

Instantly share code, notes, and snippets.

@dannvix
Created April 15, 2013 02:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save dannvix/5385384 to your computer and use it in GitHub Desktop.
Save dannvix/5385384 to your computer and use it in GitHub Desktop.
simple multithreading TCP echo server in (ugly) Java
import java.io.*;
import java.net.*;
import java.lang.Thread;
public class EchoServer {
public static void main (String[] args) {
try {
ServerSocket server = new ServerSocket(5566);
while (true) {
Socket client = server.accept();
EchoHandler handler = new EchoHandler(client);
handler.start();
}
}
catch (Exception e) {
System.err.println("Exception caught:" + e);
}
}
}
class EchoHandler extends Thread {
Socket client;
EchoHandler (Socket client) {
this.client = client;
}
public void run () {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter writer = new PrintWriter(client.getOutputStream(), true);
writer.println("[type 'bye' to disconnect]");
while (true) {
String line = reader.readLine();
if (line.trim().equals("bye")) {
writer.println("bye!");
break;
}
writer.println("[echo] " + line);
}
}
catch (Exception e) {
System.err.println("Exception caught: client disconnected.");
}
finally {
try { client.close(); }
catch (Exception e ){ ; }
}
}
}
@sethuster
Copy link

Thanks!

@AlexAbraham1
Copy link

thanks!

@zombiecircus
Copy link

thanks!

@leon0399
Copy link

leon0399 commented Dec 8, 2015

Thx!

@fletchPL
Copy link

fletchPL commented Jan 7, 2016

Thx!

@alexalghisi
Copy link

Thanks :)

@HARCHHI
Copy link

HARCHHI commented Apr 11, 2016

Thanks :)

@1brah1m
Copy link

1brah1m commented Apr 17, 2016

Can more than one client communicate with this server at the same time?

@hiroto-takatoshi
Copy link

thx!

@tujietg
Copy link

tujietg commented Feb 26, 2018

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment