-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.java
More file actions
76 lines (68 loc) · 2.38 KB
/
Copy pathserver.java
File metadata and controls
76 lines (68 loc) · 2.38 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
71
72
73
74
75
76
import java.io.*;
import java.net.*;
public class server {
public static void main(String[] args) {
new ChatServer2();
}
}
class ChatServer2 {
BufferedReader input;
PrintWriter output;
BufferedReader consoleInput;
ServerSocket serverSocket;
Socket socket;
ChatServer2() {
try {
serverSocket = new ServerSocket(12345);
System.out.println("Server is running and waiting for a client...");
socket = serverSocket.accept();
System.out.println("Client connected!");
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
output = new PrintWriter(socket.getOutputStream(), true);
consoleInput = new BufferedReader(new InputStreamReader(System.in));
startreading();
startwriting();
} catch (Exception e) {
System.out.println("Connection closed.");
}
}
public void startreading() {
Runnable r1 = () -> {
System.out.println("Reader started. Type 'exit' to terminate.");
try {
while (!socket.isClosed()) {
String msg = input.readLine();
if (msg == null || msg.equalsIgnoreCase("exit")) {
System.out.println("Client terminated the chat.");
socket.close();
break;
}
System.out.println("\n=>Client: " + msg);
}
} catch (Exception e) {
System.out.println("Reading stopped (Connection closed).");
}
};
new Thread(r1).start();
}
public void startwriting() {
Runnable r2 = () -> {
System.out.println("Writer started.");
try {
while (!socket.isClosed()) {
String msg = consoleInput.readLine();
output.println(msg);
output.flush();
if (msg.equalsIgnoreCase("exit")) {
System.out.println("Server terminated the chat.");
socket.close();
break;
}
}
} catch (Exception e) {
System.out.println("Writing stopped (Connection closed).");
}
};
new Thread(r2).start();
}
}