Client.java
1.9 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 Client {
private static final int BUFFER_SIZE = 1024;
private static final String HOST = "localhost";
private static final int PORT = 8888;
public static void main(String[] args) {
try {
SocketChannel clientChannel = SocketChannel.open();
clientChannel.configureBlocking(false);
clientChannel.connect(new InetSocketAddress(HOST, PORT));
while (!clientChannel.finishConnect()) {
// wait until connection is established
}
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);
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();
while (true) {
String message = scanner.nextLine();
buffer = ByteBuffer.wrap(message.getBytes());
clientChannel.write(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}