Client.java
2.3 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
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 Client {
private static final int BUFFER_SIZE = 1024;
private static final String HOST = "localhost";
private static final int PORT = 8877;
public static void main(String[] args) {
try {
// 创建SocketChannel对象,连接服务器。
SocketChannel clientChannel = SocketChannel.open();
clientChannel.configureBlocking(false);
clientChannel.connect(new InetSocketAddress(HOST, PORT));
while (!clientChannel.finishConnect()) {
// 如果连接未完成,等待连接完成。
}
System.out.println("Connected to server " + HOST + ":" + PORT);
System.out.println("Enter your name:");
// 读取用户输入的用户名,将其发送给服务器。
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
ByteBuffer buffer = ByteBuffer.wrap(name.getBytes());
clientChannel.write(buffer);
// 创建一个新线程,使用SocketChannel的read()方法读取服务器发送的消息,并在控制台上显示。
new Thread(() -> {
while (true) {
try {
ByteBuffer receiveBuffer = ByteBuffer.allocate(BUFFER_SIZE);
int bytesRead = clientChannel.read(receiveBuffer);
if (bytesRead > 0) {
String message = new String(receiveBuffer.array()).trim();
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
// 在主线程中,读取用户输入的消息,使用SocketChannel的write()方法将其发送给服务器。
while (true) {
String message = scanner.nextLine();
buffer = ByteBuffer.wrap(message.getBytes());
clientChannel.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}