用Java代码实现基于UDP通信的简易一对一聊天室GUI界面。 要求:1.实现客户端与服务器可以相互发送信息。2.实现将文件从客户端上传至服务器或在客户端从服务器下载文件。
时间: 2023-12-17 11:05:26 浏览: 90
以下是基于UDP通信的简易一对一聊天室GUI界面的Java代码实现:
客户端:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client extends JFrame implements ActionListener {
private JTextField messageField;
private JTextArea chatArea;
private JButton sendButton;
private JButton fileButton;
private DatagramSocket socket;
private InetAddress serverAddress;
private int serverPort;
private String username;
public Client(String username, String serverAddress, int serverPort) {
super("Chat Room - " + username);
this.username = username;
this.serverPort = serverPort;
try {
this.serverAddress = InetAddress.getByName(serverAddress);
this.socket = new DatagramSocket();
this.socket.setSoTimeout(100);
} catch (UnknownHostException | SocketException e) {
e.printStackTrace();
}
// GUI components
messageField = new JTextField();
sendButton = new JButton("Send");
fileButton = new JButton("File");
chatArea = new JTextArea();
chatArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(chatArea);
JPanel panel = new JPanel(new BorderLayout());
panel.add(messageField, BorderLayout.CENTER);
panel.add(sendButton, BorderLayout.EAST);
panel.add(fileButton, BorderLayout.WEST);
add(scrollPane, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
// Event listeners
messageField.addActionListener(this);
sendButton.addActionListener(this);
fileButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(Client.this);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
sendFile(file);
}
}
});
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void sendFile(File file) {
try {
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(file);
DatagramPacket packet;
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
packet = new DatagramPacket(buffer, bytesRead, serverAddress, serverPort);
socket.send(packet);
}
packet = new DatagramPacket(new byte[0], 0, serverAddress, serverPort);
socket.send(packet);
fis.close();
chatArea.append("File sent: " + file.getName() + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void actionPerformed(ActionEvent e) {
String message = messageField.getText();
if (!message.equals("")) {
message = username + ": " + message;
byte[] buffer = message.getBytes();
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, serverAddress, serverPort);
try {
socket.send(packet);
messageField.setText("");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void run() {
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
chatArea.append(message + "\n");
} catch (SocketTimeoutException e) {
// do nothing
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String username = JOptionPane.showInputDialog("Enter your name:");
String serverAddress = JOptionPane.showInputDialog("Enter server address:");
int serverPort = Integer.parseInt(JOptionPane.showInputDialog("Enter server port:"));
Client client = new Client(username, serverAddress, serverPort);
new Thread(client::run).start();
}
}
```
服务器:
```java
import java.io.*;
import java.net.*;
public class Server {
private DatagramSocket socket;
private int port;
public Server(int port) {
this.port = port;
try {
this.socket = new DatagramSocket(port);
this.socket.setSoTimeout(100);
} catch (SocketException e) {
e.printStackTrace();
}
}
public void run() {
byte[] buffer = new byte[1024];
while (true) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(packet);
String message = new String(packet.getData(), 0, packet.getLength());
if (message.endsWith("\n")) {
message = message.substring(0, message.length() - 1);
}
if (message.equals("")) {
continue;
}
if (message.startsWith("FILE:")) {
receiveFile(message.substring(5), packet.getAddress(), packet.getPort());
} else {
broadcast(message, packet.getAddress(), packet.getPort());
}
} catch (SocketTimeoutException e) {
// do nothing
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void broadcast(String message, InetAddress address, int port) {
message = address.getHostAddress() + ":" + port + " " + message;
byte[] buffer = message.getBytes();
for (ClientInfo client : clients) {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, client.getAddress(), client.getPort());
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void receiveFile(String filename, InetAddress address, int port) {
try {
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(filename);
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
socket.receive(packet);
if (packet.getLength() == 0) {
break;
}
fos.write(packet.getData(), 0, packet.getLength());
}
fos.close();
broadcast("File received: " + filename, address, port);
} catch (IOException e) {
e.printStackTrace();
}
}
private static class ClientInfo {
private InetAddress address;
private int port;
public ClientInfo(InetAddress address, int port) {
this.address = address;
this.port = port;
}
public InetAddress getAddress() {
return address;
}
public int getPort() {
return port;
}
}
private List<ClientInfo> clients = new ArrayList<>();
public void addClient(InetAddress address, int port) {
clients.add(new ClientInfo(address, port));
}
public void removeClient(InetAddress address, int port) {
clients.removeIf(client -> client.getAddress().equals(address) && client.getPort() == port);
}
public static void main(String[] args) {
int port = Integer.parseInt(JOptionPane.showInputDialog("Enter server port:"));
Server server = new Server(port);
new Thread(server::run).start();
}
}
```
注意:此代码只是一个演示用例,并不适用于生产环境。在实际应用中,请考虑加密、身份验证、异常处理、性能等方面的问题。
阅读全文