1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 import java.net.SocketException;
27 import java.nio.charset.StandardCharsets;
28
29 import org.newsclub.net.unix.AFUNIXSocket;
30 import org.newsclub.net.unix.AFUNIXSocketAddress;
31
32
33
34
35
36
37
38
39
40
41
42
43 public class SimpleTestClient {
44 public static void main(String[] args) throws IOException {
45 final File socketFile = new File(new File(System.getProperty("java.io.tmpdir")),
46 "junixsocket-test.sock");
47
48 boolean connected = false;
49 try (AFUNIXSocket sock = AFUNIXSocket.connectTo(AFUNIXSocketAddress.of(socketFile));
50 InputStream is = sock.getInputStream();
51 OutputStream os = sock.getOutputStream();
52 DataInputStream din = new DataInputStream(is);
53 DataOutputStream dout = new DataOutputStream(os);) {
54 System.out.println("Connected");
55 connected = true;
56
57 byte[] buf = new byte[128];
58
59 int read = is.read(buf);
60 System.out.println("Server says: " + new String(buf, 0, read, StandardCharsets.UTF_8));
61
62 System.out.println("Replying to server...");
63 os.write("Hello Server".getBytes(StandardCharsets.UTF_8));
64 os.flush();
65
66 System.out.println("Now reading numbers from the server...");
67 while (!Thread.interrupted()) {
68 int number = din.readInt();
69 if (number == -123) {
70
71
72 break;
73 }
74 System.out.println(number);
75
76 int ourNumber = number * 2;
77
78 System.out.println("Sending back " + ourNumber);
79 dout.writeInt(ourNumber);
80 }
81 } catch (SocketException e) {
82 if (!connected) {
83 System.out.println("Cannot connect to server. Have you started it?");
84 System.out.println();
85 }
86 throw e;
87 }
88
89 System.out.println("End of communication.");
90 }
91 }