MCPcopy Create free account
hub / github.com/ReadyTalk/avian / SendServer

Class SendServer

test/extra/SendServer.java:10–92  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8import java.nio.channels.SocketChannel;
9
10public class SendServer {
11 private static char cIndex = 'A';
12 private static ByteBuffer inBuf = ByteBuffer.allocate(8192);
13
14 private static void dumpByteBuffer(char note, ByteBuffer buf) {
15 System.out.println(note + ": Buffer position: " + buf.position() + " limit: " +
16 buf.limit() + " capacity: " + buf.capacity() + " remaining: " +
17 buf.remaining());
18 }
19
20 private static class Connection {
21 private final char myIndex;
22 private final java.io.FileOutputStream fos;
23
24 public Connection() throws Exception {
25 myIndex = cIndex++;
26 fos = new java.io.FileOutputStream("dump." + myIndex);
27 }
28
29 public void handleRead(SocketChannel channel) throws Exception {
30 int count = -1;
31 while ((count = channel.read(inBuf)) > 0) {
32 System.out.println(myIndex + ": read " + count);
33 }
34 inBuf.flip();
35 fos.write(inBuf.array(), inBuf.arrayOffset()+inBuf.position(), inBuf.remaining());
36 inBuf.position(inBuf.limit());
37 if (count < 0) {
38 System.out.println(myIndex + ": Closing channel");
39 fos.close();
40 channel.close();
41 }
42// dumpByteBuffer(myIndex, inBuf);
43 inBuf.compact();
44 }
45 }
46
47 public void runMainLoop() throws Exception {
48 boolean keepRunning = true;
49 int port = 8988;
50 ServerSocketChannel serverChannel = ServerSocketChannel.open();
51 try {
52 serverChannel.configureBlocking(false);
53 serverChannel.socket().bind(new InetSocketAddress("0.0.0.0", port));
54 Selector selector = Selector.open();
55 serverChannel.register(selector, SelectionKey.OP_ACCEPT, null);
56 while (keepRunning) {
57 System.out.println("Running main loop");
58 selector.select(10000);
59 for (SelectionKey key : selector.selectedKeys()) {
60 if (key.isAcceptable()) {
61 System.out.println("Accepting new connection");
62 SocketChannel c = ((ServerSocketChannel) key.channel()).accept();
63 if (c != null) {
64 c.configureBlocking(false);
65 c.register(selector, SelectionKey.OP_READ, new Connection());
66 }
67 } else {

Callers

nothing calls this directly

Calls 1

allocateMethod · 0.95

Tested by

no test coverage detected