NIOClient.java
1.8 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
package two;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class NIOClient {
public void start(String hostname, int port) throws IOException {
// 创建SocketChannel
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
socketChannel.connect(new InetSocketAddress(hostname, port));
// 等待连接完成
while (!socketChannel.finishConnect()) {
// do nothing
}
System.out.println("Connected to server " + socketChannel.getRemoteAddress());
// 循环读取用户输入,并发送到服务器
Scanner scanner = new Scanner(System.in);
new Thread(() -> {
while (true) {
try {
// 读取服务器发送的消息
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int numRead = socketChannel.read(readBuffer);
if (numRead > 0) {
String receivedMessage = new String(readBuffer.array(), 0, numRead).trim();
System.out.println("Received message from server: " + receivedMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
while (true) {
if (scanner.hasNext()){
String message = scanner.nextLine();
ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
socketChannel.write(buffer);
}
}
}
public static void main(String[] args) throws IOException {
NIOClient client = new NIOClient();
client.start("localhost", 8888);
}
}