Debian Codegraph @

junixsocket-demo/src/main/java/org/newsclub/net/unix/demo/SimpleTestServer.java

raw
1 /*
2 * junixsocket
3 *
4 * Copyright 2009-2022 Christian Kohlschütter
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 package org.newsclub.net.unix.demo;
19
20 import java.io.DataInputStream;
21 import java.io.DataOutputStream;
22 import java.io.File;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.OutputStream;
26
27 import org.newsclub.net.unix.AFUNIXServerSocket;
28 import org.newsclub.net.unix.AFUNIXSocket;
29 import org.newsclub.net.unix.AFUNIXSocketAddress;
30 import org.newsclub.net.unix.SocketClosedException;
31
32 /**
33 * A simple demo server.
34 *
35 * Sends a hello message (as a string), then reads back a response string.
36 *
37 * Finally, sends integers (via {@link DataOutputStream}) from 1 to 5, expects an integer response
38 * of twice the sent value each, then sends a "-123" magic number to indicate the end of the
39 * conversation.
40 *
41 * @author Christian Kohlschütter
42 * @see SimpleTestClient
43 */
44 public final class SimpleTestServer {
45 private static final int MAX_NUMBER = 5;
46
47 private SimpleTestServer() {
48 throw new UnsupportedOperationException("No instances");
49 }
50
51 public static void main(String[] args) throws IOException {
52 final File socketFile = new File(new File(System.getProperty("java.io.tmpdir")),
53 "junixsocket-test.sock");
54 System.out.println(socketFile);
55
56 try (AFUNIXServerSocket server = AFUNIXServerSocket.newInstance()) {
57 /*
58 * Uncomment the code below to change the bind behavior:
59 *
60 * By default ("reuseAddress" is true), attempting to bind while another server is running on
61 * the same address will cause the first server to terminate, and the new server will take
62 * over the address. Depending on the operating system, this may involve connecting to the
63 * first server in order to "wake up" the accept call.
64 *
65 * In this demo code, we use AFSocket.getConnectionStatus to see if the accepted connection is
66 * alive by sending
67 *
68 * When "reuseAddress" is false, attempting to bind while another server is running won't
69 * disrupt the first connection. The second bind will throw a SocketException instead.
70 *
71 * NOTE: "reuseAddress=true" may not yet be supported on certain operating systems, such as
72 * IBM i and z/OS. On these platforms, the behavior is as if "reuseAddress=false". Please
73 * reach out by filing an issue on https://github.com/kohlschutter/junixsocket/issues if this
74 * is a problem for you.
75 */
76 // server.setReuseAddress(false);
77
78 server.bind(AFUNIXSocketAddress.of(socketFile));
79 System.out.println("server: " + server);
80
81 while (!Thread.interrupted() && !server.isClosed()) {
82 System.out.println("Waiting for connection...");
83
84 boolean remoteReady = false;
85 try (AFUNIXSocket sock = server.accept();
86 InputStream is = sock.getInputStream();
87 OutputStream os = sock.getOutputStream();
88 DataOutputStream dout = new DataOutputStream(os);
89 DataInputStream din = new DataInputStream(is);) {
90 remoteReady = true;
91 System.out.println("Connected: " + sock);
92
93 // This check is optional. Without it, the below write may throw a "Broken pipe" exception
94 // if the remote connection was closed right after connect.
95 //
96 // The check involves sending a zero-byte message to the peer, and catching exceptions
97 // as we go. Note that this is deliberately not automated to allow code perform and detect
98 // "(port) knocking".
99 if (sock.checkConnectionClosed()) {
100 System.out.println("Peer closed socket right after connecting");
101 continue;
102 }
103
104 System.out.println("Saying hello to client " + sock);
105 os.write("Hello, dear Client".getBytes("UTF-8"));
106 os.flush();
107
108 byte[] buf = new byte[128];
109 int read = is.read(buf);
110 System.out.println("Client's response: " + new String(buf, 0, read, "UTF-8"));
111
112 System.out.println("Now counting to " + MAX_NUMBER + "...");
113 int number = 0;
114 while (!Thread.interrupted()) {
115 number++;
116 System.out.println("write " + number);
117 dout.writeInt(number);
118 try {
119 Thread.sleep(1000);
120 } catch (InterruptedException e) {
121 e.printStackTrace();
122 break;
123 }
124 if (number >= MAX_NUMBER) {
125 System.out.println("write -123 (end of numbers)");
126 dout.writeInt(-123); // in this demo, -123 is our magic number to indicate the end
127 break;
128 }
129
130 // verify the number from the client
131 // in the demo, the client just sends 2 * our number
132 int theirNumber = din.readInt();
133 System.out.println("received " + theirNumber);
134 if (theirNumber != (number * 2)) {
135 throw new IllegalStateException("Received the wrong number: " + theirNumber);
136 }
137 }
138 } catch (SocketClosedException e) {
139 if (!remoteReady) {
140 // ignore -- the remote connection terminated during accept or when trying to get the
141 // input/output streams
142 } else {
143 // unexpected
144 e.printStackTrace();
145 }
146 } catch (IOException e) {
147 // unexpected
148 e.printStackTrace();
149 }
150 }
151 } finally {
152 System.out.println("Server terminated");
153 }
154 }
155 }