1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package com.sun.akuma;
25
26 import java.net.ServerSocket;
27 import java.net.Socket;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30
31 import static com.sun.akuma.CLibrary.LIBC;
32
33
34
35
36
37
38 public class EchoServer extends NetworkServer {
39 public static void main(String[] args) throws Exception {
40 new EchoServer(args).run();
41 }
42
43 public EchoServer(String[] args) {
44 super(args);
45 }
46
47
48
49
50 @Override
51 protected boolean shouldBeDaemonized() {
52 return !arguments.isEmpty();
53 }
54
55 @Override
56 protected void frontend() throws Exception {
57 System.out.println("This is a simple echo server. Run with some argument to fork into a daemon, then try 'nc localhost 12345' from several terminals.");
58 super.frontend();
59 }
60
61 @Override
62 protected void forkWorkers(JavaVMArguments args) throws Exception {
63
64 forkWorkerThreads(args, 2);
65 }
66
67 @Override
68 protected ServerSocket createServerSocket() throws Exception {
69 System.out.println("Listening on port 12345");
70
71 return new ServerSocket(12345);
72 }
73
74 @Override
75 protected void worker(ServerSocket ss) throws Exception {
76 byte[] buf = new byte[1024];
77
78 while(true) {
79 Socket s = ss.accept();
80 System.out.println("PID:"+ LIBC.getpid()+" accepted a new connection");
81
82 InputStream in = s.getInputStream();
83 OutputStream out = s.getOutputStream();
84
85 int len;
86 while((len=in.read(buf))>=0)
87 out.write(buf,0,len);
88
89 s.close();
90 }
91 }
92 }