-
-
Save solomax/9323575 to your computer and use it in GitHub Desktop.
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.*; | |
import java.util.Date; | |
import java.lang.Thread; | |
public class EchoServer { | |
public static final int DEFAULT_PORT = 9004; | |
public static final long DEFAULT_SLEEP = -1L; | |
private int port = DEFAULT_PORT; | |
static private long sleep = DEFAULT_SLEEP; | |
public static void main(String[] args) throws IOException { | |
new EchoServer(args).start(); | |
} | |
EchoServer(String[] args) { | |
try { | |
port = Integer.parseInt(args[0]); | |
System.out.println("port: " + port); | |
} catch (Exception e) { | |
//no-op | |
} | |
try { | |
sleep = Long.parseLong(args[1]); | |
System.out.println("sleep: " + sleep); | |
} catch (Exception e) { | |
//no-op | |
} | |
} | |
void start() throws IOException { | |
ServerSocket server = null; | |
try { | |
server = new ServerSocket(port); | |
while (true) { | |
Socket client = server.accept(); | |
new EchoHandler(client).start(); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} finally { | |
if (server != null) { | |
server.close(); | |
} | |
} | |
} | |
static class EchoHandler extends Thread { | |
Socket client; | |
EchoHandler(Socket client) { | |
this.client = client; | |
} | |
public void run() { | |
try { | |
Date start = new Date(); | |
byte[] b = new byte[1024]; //should be simple | |
int read = client.getInputStream().read(b); | |
if (sleep > 0) { | |
Thread.sleep(sleep); | |
} | |
client.getOutputStream().write(b, 0, read); | |
Date end = new Date(); | |
System.out.println("recieved: " + start + "; processed: " + end + "; elapsed: " + (end.getTime() - start.getTime())); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} finally { | |
try { | |
client.close(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment