-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatClient.java
More file actions
59 lines (52 loc) · 2.2 KB
/
Copy pathChatClient.java
File metadata and controls
59 lines (52 loc) · 2.2 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
import java.awt.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
// ChatClient: connects to server, shows GUI, sends/receives messages
public class ChatClient {
private BufferedReader in; // to read messages from server
private PrintWriter out; // to send messages to server
private JFrame frame = new JFrame("Chat App"); // main window
private JTextArea messageArea = new JTextArea(15, 40); // chat history
private JTextField textField = new JTextField(40); // input field
private String role; // "Student" or "Teacher"
public ChatClient(String role) {
this.role = role;
// GUI setup
messageArea.setEditable(false);
frame.getContentPane().add(new JScrollPane(messageArea), BorderLayout.CENTER);
frame.getContentPane().add(textField, BorderLayout.SOUTH);
frame.pack();
// When user presses Enter, send message tagged with role
textField.addActionListener(e -> {
out.println(role + ": " + textField.getText());
textField.setText("");
});
}
private void connectToServer() throws IOException {
// Connect to server at localhost:1234
Socket socket = new Socket("localhost", 1234);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
// Thread to continuously listen for incoming messages
new Thread(() -> {
try {
String message;
while ((message = in.readLine()) != null) {
// Append received message to chat history
messageArea.append(message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
public static void main(String[] args) throws Exception {
// Ask user to enter role (Student or Teacher)
String role = JOptionPane.showInputDialog("Enter role: Student or Teacher");
ChatClient client = new ChatClient(role);
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setVisible(true);
client.connectToServer();
}
}