写代码用Java的socket通信实现多人多线程聊天室,客户端采用图形界面并有加入聊天室和退出聊天室的选项
时间: 2024-02-20 16:00:44 浏览: 99
好的,我会尽力回答您的问题。
首先需要了解一下Java的Socket通信,Socket是一种网络通信协议,它是一种应用层协议,用于实现进程间的通信和网络间的通信。
在Java中,可以通过java.net包中的Socket类和ServerSocket类来实现Socket通信。
为了实现多人多线程聊天室,我们需要采用ServerSocket类来实现服务器端,客户端可以采用Socket类来实现。
以下是大致的代码实现:
服务端:
```java
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private ServerSocket server;
private ArrayList<Socket> clients;
public Server(int port) {
clients = new ArrayList<>();
try {
server = new ServerSocket(port);
System.out.println("Server started.");
} catch (IOException e) {
System.out.println("Failed to start server.");
e.printStackTrace();
System.exit(-1);
}
}
public void start() {
while (true) {
try {
Socket client = server.accept();
clients.add(client);
ClientHandler handler = new ClientHandler(client, clients);
new Thread(handler).start();
System.out.println("New client connected.");
} catch (IOException e) {
System.out.println("Client connection error.");
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Server server = new Server(8888);
server.start();
}
}
class ClientHandler implements Runnable {
private Socket client;
private ArrayList<Socket> clients;
private BufferedReader in;
private PrintWriter out;
public ClientHandler(Socket client, ArrayList<Socket> clients) {
this.client = client;
this.clients = clients;
try {
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
System.out.println("Failed to create input/output stream.");
e.printStackTrace();
}
}
@Override
public void run() {
try {
String name = in.readLine();
System.out.println("New client " + name + " connected.");
out.println("Welcome " + name + " to the chat room.");
for (Socket c : clients) {
if (!c.equals(client)) {
PrintWriter p = new PrintWriter(c.getOutputStream(), true);
p.println(name + " has joined the chat room.");
}
}
String line;
while ((line = in.readLine()) != null) {
System.out.println(name + ": " + line);
for (Socket c : clients) {
if (!c.equals(client)) {
PrintWriter p = new PrintWriter(c.getOutputStream(), true);
p.println(name + ": " + line);
}
}
}
clients.remove(client);
for (Socket c : clients) {
PrintWriter p = new PrintWriter(c.getOutputStream(), true);
p.println(name + " has left the chat room.");
}
client.close();
System.out.println("Client " + name + " disconnected.");
} catch (IOException e) {
System.out.println("Failed to communicate with the client.");
e.printStackTrace();
}
}
}
```
客户端:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class Client extends JFrame {
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private JTextArea messageArea;
private JTextField messageField;
private JButton sendButton;
private JButton joinButton;
private JButton exitButton;
private boolean connected;
public Client() {
super("Chat Room");
connected = false;
messageArea = new JTextArea();
messageArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(messageArea);
messageField = new JTextField();
sendButton = new JButton("Send");
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
sendMessage();
}
});
joinButton = new JButton("Join");
joinButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
joinChatRoom();
}
});
exitButton = new JButton("Exit");
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
exitChatRoom();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 3));
buttonPanel.add(joinButton);
buttonPanel.add(exitButton);
buttonPanel.add(sendButton);
JPanel messagePanel = new JPanel();
messagePanel.setLayout(new BorderLayout());
messagePanel.add(scrollPane, BorderLayout.CENTER);
messagePanel.add(messageField, BorderLayout.SOUTH);
messagePanel.add(buttonPanel, BorderLayout.NORTH);
setContentPane(messagePanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 300);
setVisible(true);
}
private void sendMessage() {
if (connected) {
String message = messageField.getText();
if (!message.equals("")) {
out.println(message);
messageField.setText("");
}
}
}
private void joinChatRoom() {
if (!connected) {
String name = JOptionPane.showInputDialog(this, "Please enter your name:");
if (name != null && !name.equals("")) {
try {
socket = new Socket("localhost", 8888);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println(name);
messageArea.append(in.readLine() + "\n");
connected = true;
joinButton.setEnabled(false);
exitButton.setEnabled(true);
sendButton.setEnabled(true);
Thread listener = new Thread(new MessageListener());
listener.start();
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Failed to connect to the server.");
e.printStackTrace();
}
}
}
}
private void exitChatRoom() {
if (connected) {
out.println("exit");
connected = false;
joinButton.setEnabled(true);
exitButton.setEnabled(false);
sendButton.setEnabled(false);
try {
socket.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Failed to close the socket.");
e.printStackTrace();
}
}
}
class MessageListener implements Runnable {
@Override
public void run() {
try {
String line;
while ((line = in.readLine()) != null) {
messageArea.append(line + "\n");
}
} catch (IOException e) {
JOptionPane.showMessageDialog(Client.this, "Failed to receive message from the server.");
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Client client = new Client();
}
}
```
以上就是基于Java的Socket通信实现多人多线程聊天室的大致代码,客户端采用图形界面并有加入聊天室和退出聊天室的选项。
阅读全文