-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClientSelector.java
More file actions
70 lines (60 loc) · 1.62 KB
/
ChatClientSelector.java
File metadata and controls
70 lines (60 loc) · 1.62 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
package il.co.ilrd.chatselectors;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
public class ChatClientSelector {
private String name;
private SocketChannel socket;
private BufferedReader consoleInput;
public ChatClientSelector(String ip, int port, String name) {
try {
InetSocketAddress host = new InetSocketAddress(ip, port);
socket = SocketChannel.open(host);
} catch (IOException e) {
e.printStackTrace();
}
this.name = name;
}
public void run() {
Thread consoleInputThread = new Thread(this::recieveConsoleInput);
Thread serverInputThread = new Thread(this::recieveServerInput);
consoleInputThread.start();
serverInputThread.start();
}
private void sendInput(String str) {
String message = name + ":" + str;
try {
byte[] byteMessage = message.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(byteMessage);
socket.write(buffer);
buffer.clear();
} catch (IOException e) {
e.printStackTrace();
}
}
private void recieveConsoleInput() {
while (socket.isConnected()) {
consoleInput = new BufferedReader(new InputStreamReader(System.in));
try {
sendInput(consoleInput.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void recieveServerInput() {
while (socket.isConnected()) {
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
while (socket.read(buf) > 0) {
System.out.println(new String(buf.array()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}