JAVA可以用windowBuilder写的多人聊天室,代码
时间: 2024-02-05 07:13:05 浏览: 109
java可视化控件制作流程,源码
以下是使用Java和WindowBuilder构建多人聊天室的示例代码:
```
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
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;
import javax.swing.border.EmptyBorder;
public class MultiChatServer extends JFrame {
private JPanel contentPane;
private JTextArea textArea;
private JTextField textField;
private JButton btnSend;
private ServerSocket serverSocket;
private int port = 9001;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MultiChatServer frame = new MultiChatServer();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MultiChatServer() {
setTitle("Multi Chat Server");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
contentPane.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.SOUTH);
textField = new JTextField();
panel.add(textField);
textField.setColumns(30);
btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String message = textField.getText();
sendToAll(message);
}
});
panel.add(btnSend);
setVisible(true);
try {
serverSocket = new ServerSocket(port);
while (true) {
Socket socket = serverSocket.accept();
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendToAll(String message) {
textArea.append("[Server] " + message + "\n");
for (ClientHandler handler : ClientHandler.clients) {
handler.sendMessage(message);
}
}
private class ClientHandler implements Runnable {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private static final String DELIMITER = "> ";
public static final String END_SESSION = "END_SESSION";
private static final String JOIN_MESSAGE = " joined the chat.";
private static final String EXIT_MESSAGE = " left the chat.";
private static final String WELCOME_MESSAGE = "Welcome to the chat room!";
private static final String DISCONNECTED_MESSAGE = "You have been disconnected from the chat room.";
private static final String ERROR_MESSAGE = "An error occurred. Please try again later.";
private static final String USERNAME_PROMPT_MESSAGE = "Please enter your username:";
private String username;
private static final int MAX_USERNAME_LENGTH = 20;
public static final int MAX_MESSAGE_LENGTH = 200;
public static final int MAX_CONNECTIONS = 10;
public static final int READ_TIMEOUT = 1000;
public static final int WRITE_TIMEOUT = 1000;
public static final int CONNECT_TIMEOUT = 1000;
public static final int DISCONNECT_TIMEOUT = 1000;
public static final int SERVER_PORT = 9001;
public static final String SERVER_ADDRESS = "localhost";
public static final String CHARSET = "UTF-8";
public static final int BUFFER_SIZE = 1024;
public static final int BACKLOG = 50;
public static final int MAX_RETRIES = 10;
public static final int RETRY_DELAY = 100;
public static final int MAX_USERNAME_RETRIES = 3;
public static final int USERNAME_RETRY_DELAY = 100;
public static final String HELP_MESSAGE = "Type /help to see this message again.\n"
+ "Type /quit to quit the chat.\n" + "Type /users to see the list of online users.\n"
+ "Type /msg [username] [message] to send a private message to a user.\n";
public static final String QUIT_COMMAND = "/quit";
public static final String USERS_COMMAND = "/users";
public static final String MSG_COMMAND = "/msg";
public static final String HELP_COMMAND = "/help";
private static int idGenerator = 0;
private int id;
private static final String MSG_DELIMITER = " ";
public static final String USERNAME_TAKEN_MESSAGE = "Sorry, that username is already taken. Please try another.";
private static final String INVALID_COMMAND_MESSAGE = "Invalid command. Type /help for a list of commands.";
private static final String PRIVATE_MESSAGE_PREFIX = "[Private message from ";
private static final String PRIVATE_MESSAGE_SUFFIX = "] ";
private static final String USERNAME_CHANGE_COMMAND = "/username";
private static final String USERNAME_CHANGE_SUCCESS_MESSAGE = "Your username has been changed to ";
private static final String USERNAME_CHANGE_FAILURE_MESSAGE = "Sorry, your username could not be changed. Please try again later.";
private static final String USERNAME_CHANGE_PROMPT_MESSAGE = "Please enter your new username:";
private static final String USERNAME_CHANGE_DELIMITER = " ";
private static final String USERNAME_CHANGE_COMMAND_PATTERN = "^\\/username\\s.+";
public ClientHandler(Socket socket) {
this.socket = socket;
id = idGenerator++;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream(), CHARSET));
out = new PrintWriter(socket.getOutputStream(), true);
sendMessage(USERNAME_PROMPT_MESSAGE);
for (int i = 0; i < MAX_USERNAME_RETRIES; i++) {
String input = readLineWithTimeout(READ_TIMEOUT);
if (input != null && input.length() <= MAX_USERNAME_LENGTH) {
username = input.trim();
if (isUsernameUnique(username)) {
sendMessage(WELCOME_MESSAGE);
broadcast(JOIN_MESSAGE);
clients.add(this);
break;
} else {
sendMessage(USERNAME_TAKEN_MESSAGE);
}
} else {
sendMessage(ERROR_MESSAGE);
}
}
if (username == null) {
disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean isUsernameUnique(String username) {
for (ClientHandler handler : clients) {
if (handler.username == null) {
continue;
}
if (handler.username.equals(username)) {
return false;
}
}
return true;
}
private void broadcast(String message) {
for (ClientHandler handler : clients) {
if (handler == this) {
continue;
}
handler.sendMessage(message);
}
}
private void sendMessage(String message) {
out.println(message);
}
@Override
public void run() {
try {
while (true) {
String input = readLineWithTimeout(READ_TIMEOUT);
if (input == null) {
continue;
}
if (input.equals(QUIT_COMMAND)) {
break;
}
if (input.startsWith(MSG_COMMAND)) {
handlePrivateMessage(input);
} else if (input.equals(USERS_COMMAND)) {
handleUsersCommand();
} else if (input.equals(HELP_COMMAND)) {
sendMessage(HELP_MESSAGE);
} else if (input.matches(USERNAME_CHANGE_COMMAND_PATTERN)) {
handleUsernameChange(input);
} else {
broadcast(username + DELIMITER + input);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
disconnect();
}
}
private void handlePrivateMessage(String input) {
String[] tokens = input.split(MSG_DELIMITER);
if (tokens.length < 3) {
sendMessage(INVALID_COMMAND_MESSAGE);
return;
}
String recipient = tokens[1];
String message = input.substring(MSG_COMMAND.length() + recipient.length() + 2);
for (ClientHandler handler : clients) {
if (handler.username == null) {
continue;
}
if (handler.username.equals(recipient)) {
String privateMessage = PRIVATE_MESSAGE_PREFIX + username + PRIVATE_MESSAGE_SUFFIX + message;
handler.sendMessage(privateMessage);
sendMessage(privateMessage);
return;
}
}
sendMessage("User " + recipient + " is not online.");
}
private void handleUsersCommand() {
StringBuilder builder = new StringBuilder();
builder.append("Online users:\n");
for (ClientHandler handler : clients) {
if (handler.username != null) {
builder.append(handler.username + "\n");
}
}
sendMessage(builder.toString());
}
private void handleUsernameChange(String input) {
String newUsername = input.substring(USERNAME_CHANGE_COMMAND.length() + 1);
if (!isUsernameUnique(newUsername)) {
sendMessage(USERNAME_TAKEN_MESSAGE);
return;
}
String oldUsername = username;
username = newUsername;
broadcast(oldUsername + " changed their username to " + newUsername + ".");
sendMessage(USERNAME_CHANGE_SUCCESS_MESSAGE + newUsername + ".");
}
private void disconnect() {
clients.remove(this);
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
broadcast(EXIT_MESSAGE);
sendMessage(DISCONNECTED_MESSAGE);
}
private String readLineWithTimeout(int timeout) throws IOException {
socket.setSoTimeout(timeout);
StringBuilder builder = new StringBuilder();
char[] buffer = new char[BUFFER_SIZE];
int charsRead = 0;
while (true) {
int charsReadThisTime = in.read(buffer, 0, BUFFER_SIZE);
if (charsReadThisTime == -1) {
break;
}
builder.append(buffer, 0, charsReadThisTime);
charsRead += charsReadThisTime;
if (builder.toString().endsWith("\n")) {
break;
}
}
if (charsRead > 0) {
return builder.toString().trim();
} else {
return null;
}
}
}
}
```
这段代码使用了Java的Socket和ServerSocket实现了一个简单的聊天室服务器,可以让多个客户端连接并交换消息。该代码使用了WindowBuilder图形界面构建工具,因此具有可视化的用户界面。
阅读全文