Created
April 15, 2013 02:55
-
-
Save dannvix/5385384 to your computer and use it in GitHub Desktop.
simple multithreading TCP echo server in (ugly) Java
This file contains hidden or 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.*; | |
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 ){ ; } | |
} | |
} | |
} |
thanks!
thanks!
Thx!
Thx!
Thanks :)
Thanks :)
Can more than one client communicate with this server at the same time?
thx!
thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!