请写出服务器端的gui界面java代码
时间: 2023-11-28 18:05:20 浏览: 148
以下是一个简单的基于Java的GUI聊天服务器端代码示例:
```java
import javax.swing.*;
import java.awt.*;
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 java.util.ArrayList;
public class ChatServer extends JFrame {
private JTextArea chatArea;
private JTextField messageField;
private ArrayList<PrintWriter> clientWriters;
public ChatServer() {
setTitle("Chat Server");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
chatArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(chatArea);
add(scrollPane, BorderLayout.CENTER);
messageField = new JTextField();
messageField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sendMessageToAllClients();
}
});
add(messageField, BorderLayout.SOUTH);
setVisible(true);
startServer();
}
private void startServer() {
clientWriters = new ArrayList<>();
try {
ServerSocket serverSocket = new ServerSocket(5000);
while (true) {
Socket clientSocket = serverSocket.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
clientWriters.add(writer);
new Thread(new ClientHandler(clientSocket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessageToAllClients() {
String message = messageField.getText();
for (PrintWriter writer : clientWriters) {
writer.println("Server: " + message);
}
chatArea.append("Server: " + message + "\n");
messageField.setText("");
}
private class ClientHandler implements Runnable {
private Socket clientSocket;
private BufferedReader reader;
public ClientHandler(Socket socket) {
clientSocket = socket;
try {
reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
for (PrintWriter writer : clientWriters) {
writer.println(message);
}
chatArea.append(message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ChatServer();
}
});
}
}
```
这是一个简单的聊天服务器端,它监听本地主机上的端口5000,并接受来自客户端的连接。当有新的客户端连接时,将为每个客户端启动一个新的线程来处理客户端的消息。服务器将接收来自客户端的消息,并将其转发给所有已连接的客户端。在服务器窗口中,您可以通过在文本框中输入消息并按下回车键来发送消息给所有客户端。
阅读全文