-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
105 lines (94 loc) · 3.57 KB
/
Copy pathClient.java
File metadata and controls
105 lines (94 loc) · 3.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package com.codve.aio;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
public class Client extends Thread implements CompletionHandler<Void, Client> {
private AsynchronousSocketChannel client;
private String host;
private int port;
private CountDownLatch latch;
public Client(String host, int port) {
this.host = host;
this.port = port;
try {
client = AsynchronousSocketChannel.open();
} catch (IOException e) {
throw new RuntimeException();
}
}
@Override
public void run() {
latch = new CountDownLatch(1);
// 第二个参数是连接成功后返回的参数
// 第三个参数是连接成功后的回调
client.connect(new InetSocketAddress(host, port), this, this);
try {
latch.await();
client.close();
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void completed(Void result, Client attachment) {
byte[] request = "what's the time?".getBytes(StandardCharsets.UTF_8);
ByteBuffer writeBuffer = ByteBuffer.allocate(request.length);
writeBuffer.put(request);
writeBuffer.flip();
client.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer buffer) {
if (buffer.hasRemaining()) {
client.write(buffer, buffer, this);
} else {
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
client.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer buffer) {
buffer.flip();
byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
String response = new String(bytes, StandardCharsets.UTF_8);
System.out.println("response: " + response);
latch.countDown();
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
client.close();
latch.countDown();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
client.close();
latch.countDown();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
@Override
public void failed(Throwable exc, Client attachment) {
try {
client.close();
latch.countDown();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
new Client("127.0.0.1", 8888).start();
}
}