javaCopy code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class ChatClient extends JFrame implements ActionListener {
// Components of the chat client
private static final long serialVersionUID = 1L;
private JTextField msg_input;
private JTextArea chat_area;
private JButton send;
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to receive the port number
public ChatClient(String address, int port) {
// GUI components
setLayout(new BorderLayout());
// Chat area
chat_area = new JTextArea();
chat_area.setEditable(false);
add(new JScrollPane(chat_area), BorderLayout.CENTER);
// Message input field
msg_input = new JTextField();
add(msg_input, BorderLayout.SOUTH);
msg_input.addActionListener(this);
// Send button
send = new JButton("Send");
add(send, BorderLayout.EAST);
send.addActionListener(this);
setSize(500, 500);
setVisible(true);
// Establish a connection
try {
socket = new Socket(address, port);
System.out.println("Connected");
// Takes input from the client socket
input = new DataInputStream(socket.getInputStream());
// Sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u) {
System.out.println(u);
}
catch(IOException i) {
System.out.println(i);
}
// Start a new thread for receiving messages
new Thread(new Runnable() {
public void run() {
String line = "";
while (true) {
try {
line = input.readUTF();
chat_area.append(line + "\n");
}
catch(IOException i) {
System.out.println(i);
}
}
}
}).start();
// Send a default welcome message
try {
out.writeUTF("New client joined: " + socket);
}
catch(IOException i) {
System.out.println(i);
}
}
public void actionPerformed(ActionEvent e) {
String message = msg_input.getText().trim();
if (message.equals("")) {
return;
}
msg_input.setText("");
try {
out.writeUTF(message);
}
catch(IOException i) {
System.out.println(i);
}
}
public static void main(String args[]) {
ChatClient client = new ChatClient("127.0.0.1", 5000);
}
}