请帮我写一个java的聊天室的前后台代码
时间: 2023-04-02 17:02:15 浏览: 124
好的,我可以回答这个问题。以下是一个简单的 Java 聊天室的前后台代码示例:
后台代码:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ChatServer {
private static final int PORT = 1234;
private static ArrayList<ChatHandler> handlers = new ArrayList<ChatHandler>();
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(PORT);
System.out.println("Chat server started on port " + PORT);
while (true) {
Socket client = server.accept();
System.out.println("Accepted connection from " + client.getInetAddress().getHostName());
ChatHandler handler = new ChatHandler(client);
handlers.add(handler);
handler.start();
}
} catch (IOException e) {
System.out.println("Error starting chat server: " + e.getMessage());
}
}
public static void broadcast(String message) {
for (ChatHandler handler : handlers) {
handler.sendMessage(message);
}
}
}
class ChatHandler extends Thread {
private Socket client;
private String name;
private boolean connected = true;
public ChatHandler(Socket client) {
this.client = client;
}
public void run() {
try {
ChatServer.broadcast(name + " has joined the chat.");
while (connected) {
String message = readMessage();
if (message.startsWith("/name ")) {
name = message.substring(6);
ChatServer.broadcast(name + " has changed their name.");
} else if (message.startsWith("/quit")) {
connected = false;
ChatServer.broadcast(name + " has left the chat.");
} else {
ChatServer.broadcast(name + ": " + message);
}
}
client.close();
} catch (IOException e) {
System.out.println("Error handling chat client: " + e.getMessage());
}
}
public void sendMessage(String message) {
try {
client.getOutputStream().write(message.getBytes());
} catch (IOException e) {
System.out.println("Error sending message to client: " + e.getMessage());
}
}
private String readMessage() throws IOException {
byte[] buffer = new byte[1024];
int bytesRead = client.getInputStream().read(buffer);
return new String(buffer, , bytesRead);
}
}
前台代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.Socket;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ChatClient extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private static final String SERVER_ADDRESS = "localhost";
private static final int SERVER_PORT = 1234;
private Socket socket;
private JTextArea chatArea;
private JTextField messageField;
public ChatClient() {
setTitle("Chat Client");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
chatArea = new JTextArea();
chatArea.setEditable(false);
chatArea.setFont(new Font("Arial", Font.PLAIN, 12));
chatArea.setForeground(Color.BLACK);
JScrollPane scrollPane = new JScrollPane(chatArea);
scrollPane.setPreferredSize(new Dimension(580, 320));
messageField = new JTextField();
messageField.setFont(new Font("Arial", Font.PLAIN, 12));
messageField.addActionListener(this);
JButton sendButton = new JButton("Send");
sendButton.setFont(new Font("Arial", Font.PLAIN, 12));
sendButton.addActionListener(this);
JPanel messagePanel = new JPanel(new BorderLayout());
messagePanel.add(messageField, BorderLayout.CENTER);
messagePanel.add(sendButton, BorderLayout.EAST);
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(messagePanel, BorderLayout.SOUTH);
setVisible(true);
connectToServer();
}
public void actionPerformed(ActionEvent e) {
String message = messageField.getText();
if (!message.isEmpty()) {
try {
socket.getOutputStream().write(message.getBytes());
} catch (IOException ex) {
System.out.println("Error sending message to server: " + ex.getMessage());
}
messageField.setText("");
}
}
private void connectToServer() {
try {
socket = new Socket(SERVER_ADDRESS, SERVER_PORT);
System.out.println("Connected to chat server on " + SERVER_ADDRESS + ":" + SERVER_PORT);
Thread listener = new Thread(new ChatListener(socket, chatArea));
listener.start();
} catch (IOException e) {
System.out.println("Error connecting to chat server: " + e.getMessage());
}
}
public static void main(String[] args) {
new ChatClient();
}
}
class ChatListener implements Runnable {
private Socket socket;
private JTextArea chatArea;
public ChatListener(Socket socket, JTextArea chatArea) {
this.socket = socket;
this.chatArea = chatArea;
}
public void run() {
try {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = socket.getInputStream().read(buffer)) != -1) {
String message = new String(buffer, , bytesRead);
chatArea.append(message + "\n");
}
socket.close();
} catch (IOException e) {
System.out.println("Error receiving message from server: " + e.getMessage());
}
}
}
阅读全文