-
Notifications
You must be signed in to change notification settings - Fork 0
/
Worker.java
88 lines (75 loc) · 2.73 KB
/
Worker.java
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
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Worker {
public Socket socket;
public BufferedWriter bufferedWriter;
public BufferedReader bufferedReader;
public String username;
public Worker(Socket socket, String username) {
try {
this.socket = socket;
this.bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
this.username = username;
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
public void sendMessage() {
try {
bufferedWriter.write(username);
bufferedWriter.newLine();
bufferedWriter.flush();
Scanner scanner = new Scanner(System.in);
while (socket.isConnected()) {
String messageToSend = scanner.nextLine();
bufferedWriter.write(username + "-worker: " + messageToSend);
bufferedWriter.newLine();
bufferedWriter.flush();
}
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
public void listenForMessage() {
new Thread(new Runnable() {
@Override
public void run() {
String msgFromGroupChat;
while (socket.isConnected()) {
try {
msgFromGroupChat = bufferedReader.readLine();
System.out.println(msgFromGroupChat);
} catch (IOException e) {
closeEverything(socket, bufferedReader, bufferedWriter);
}
}
}
}).start();
}
public void closeEverything(Socket socket, BufferedReader bufferedReader, BufferedWriter bufferedWriter) {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws UnknownHostException, IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("What is your worker name : ");
String username = scanner.nextLine();
Socket socket = new Socket("localhost", 1234);
Worker worker = new Worker(socket, username);
worker.listenForMessage();
worker.sendMessage();
}
}