-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient.java
More file actions
68 lines (59 loc) · 2.33 KB
/
ChatClient.java
File metadata and controls
68 lines (59 loc) · 2.33 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
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ChatServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
System.out.println("Server started. Waiting for clients...");
Socket socket = serverSocket.accept();
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
Thread receiveThread = new Thread(() -> {
try {
String message;
while ((message = in.readLine()) != null) {
System.out.println("Client: " + message);
}
} catch (IOException e) {
System.out.println("Connection closed.");
}
});
receiveThread.start();
while (true) {
String message = scanner.nextLine();
out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ChatClient {
public static void main(String[] args) {
try (Socket socket = new Socket("localhost", 12345)) {
System.out.println("Connected to server.");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
Scanner scanner = new Scanner(System.in);
Thread receiveThread = new Thread(() -> {
try {
String message;
while ((message = in.readLine()) != null) {
System.out.println("Server: " + message);
}
} catch (IOException e) {
System.out.println("Connection closed.");
}
});
receiveThread.start();
while (true) {
String message = scanner.nextLine();
out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}