1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.newsclub.net.unix.selftest.apps;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.nio.ByteBuffer;
24 import java.nio.channels.ClosedChannelException;
25 import java.nio.channels.SocketChannel;
26 import java.util.concurrent.ExecutionException;
27
28 import org.newsclub.net.unix.AFAddressFamily;
29 import org.newsclub.net.unix.AFOutputStream;
30 import org.newsclub.net.unix.AFSocket;
31 import org.newsclub.net.unix.AFSocketAddress;
32 import org.newsclub.net.unix.server.AFSocketServer;
33
34 public class ZeroServer {
35 private static void printHelp() {
36 System.err.println("Syntax: java " + ZeroServer.class.getName() + " <URI>");
37 System.err.println();
38 System.err.println("Supported schemes: " + AFAddressFamily.uriSchemes());
39 }
40
41 public static void main(String[] args) throws IOException, InterruptedException,
42 ExecutionException {
43 if (args.length == 0) {
44 printHelp();
45 System.exit(1);
46 return;
47 }
48
49 AFSocketAddress address;
50 try {
51 address = SocketAddressUtil.parseAddress(args[0]);
52 } catch (Exception e) {
53 printHelp();
54 System.err.println();
55 e.printStackTrace();
56 System.exit(1);
57 return;
58 }
59
60 new AFSocketServer<AFSocketAddress>(address) {
61 @Override
62 protected void doServeSocket(AFSocket<?> sock) throws IOException {
63 System.out.println("Connected: " + sock);
64 long numBytes = -1;
65 try {
66
67 File devZeroFile = new File("/dev/zero");
68 if (devZeroFile.exists() && Boolean.parseBoolean(System.getProperty("useDevZero",
69 "true"))) {
70 System.out.println("Streaming /dev/zero");
71 try (FileInputStream fin = new FileInputStream(devZeroFile);
72 AFOutputStream out = sock.getOutputStream()) {
73 numBytes = out.transferFrom(fin);
74 }
75 } else {
76 System.out.println("Streaming empty ByteBuffer");
77 ByteBuffer buf = ByteBuffer.allocate(8192);
78 sock.setSendBufferSize(8192);
79 sock.setSoTimeout(1);
80 numBytes = 0;
81 try (SocketChannel out = sock.getChannel()) {
82 while (!Thread.interrupted()) {
83 numBytes += out.write(buf);
84 buf.rewind();
85 }
86 } catch (ClosedChannelException e) {
87
88 }
89 }
90 } finally {
91 System.out.println("Disconnected: " + sock + "; written bytes: " + (numBytes == -1
92 ? "unknown" : numBytes));
93 }
94 }
95 }.startAndWaitToBecomeReady();
96 System.out.println("Server ready, listening on " + address);
97 }
98 }