1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.newsclub.net.unix.demo.server;
19
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.net.Socket;
26 import java.net.SocketAddress;
27 import java.nio.charset.StandardCharsets;
28
29 import org.newsclub.net.unix.AFUNIXSocket;
30
31
32
33
34
35
36
37 @SuppressWarnings("CatchAndPrintStackTrace" )
38 public final class SendFileHandleServer extends DemoServerBase {
39 private final File file;
40
41 public SendFileHandleServer(SocketAddress listenAddress, File file) {
42 super(listenAddress);
43 this.file = file;
44 }
45
46 @Override
47 protected void doServeSocket(Socket socket) throws IOException {
48 if (!(socket instanceof AFUNIXSocket)) {
49 throw new UnsupportedOperationException("File handles can only be sent via UNIX sockets");
50 }
51 doServeSocket((AFUNIXSocket) socket);
52 }
53
54 private void doServeSocket(AFUNIXSocket socket) throws IOException {
55 try (InputStream is = socket.getInputStream();
56 OutputStream os = socket.getOutputStream();
57 FileInputStream fin = new FileInputStream(file)) {
58 socket.setOutboundFileDescriptors(fin.getFD());
59 os.write("FD sent via ancillary message.".getBytes(StandardCharsets.UTF_8));
60 }
61 }
62 }