Java聊天室中使用回车键发送消息的代码
时间: 2024-02-06 11:12:43 浏览: 92
可以使用以下代码实现在Java聊天室中使用回车键发送消息:
```java
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String message = textField.getText();
// 将消息发送到聊天室
textField.setText(""); // 清空输入框
}
});
```
在上述代码中,`textField` 是用于输入消息的文本框,`addActionListener` 方法可以监听用户在文本框中按下回车键的事件。当用户按下回车键时,`actionPerformed` 方法会被调用,其中可以获取用户输入的消息并将其发送到聊天室。最后,清空输入框以便用户继续输入下一条消息。
相关问题
java代码 个人聊天室 要求: 1. 可使用文字聊天 2. 可以发送文件 3. 可以私聊 代码
好的,下面是一个简单的Java聊天室的代码示例,包含了文字聊天、文件传输和私聊功能。请注意,这只是一个示例,可能还需要完善和改进。另外,为了保证代码的简洁性,我省略了一些异常处理和其他细节,实际应用中需要注意。
Server.java
```
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
private static final int PORT = 12345;
private static Map<String, Socket> clients = new HashMap<>();
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(PORT);
System.out.println("Server started at port " + PORT);
while (true) {
Socket client = server.accept();
new Thread(new ClientHandler(client)).start();
}
}
private static class ClientHandler implements Runnable {
private Socket client;
private DataInputStream in;
private DataOutputStream out;
private String name;
public ClientHandler(Socket client) {
this.client = client;
}
public void run() {
try {
in = new DataInputStream(client.getInputStream());
out = new DataOutputStream(client.getOutputStream());
name = in.readUTF();
clients.put(name, client);
broadcast(name + " joined the chat");
while (true) {
String message = in.readUTF();
if (message.startsWith("/private")) {
String[] tokens = message.split("\\s+", 3);
String target = tokens[1];
String text = tokens[2];
if (clients.containsKey(target)) {
Socket targetClient = clients.get(target);
DataOutputStream targetOut = new DataOutputStream(targetClient.getOutputStream());
targetOut.writeUTF(name + " (private): " + text);
} else {
out.writeUTF("Error: " + target + " not found");
}
} else if (message.startsWith("/file")) {
String[] tokens = message.split("\\s+", 2);
String filename = tokens[1];
File file = new File(filename);
if (!file.exists()) {
out.writeUTF("Error: " + filename + " not found");
} else {
out.writeUTF("Sending file " + filename + " to all clients...");
broadcastFile(name, file);
}
} else {
broadcast(name + ": " + message);
}
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
client.close();
clients.remove(name);
broadcast(name + " left the chat");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
private void broadcast(String message) throws IOException {
for (Socket client : clients.values()) {
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeUTF(message);
}
}
private void broadcastFile(String sender, File file) throws IOException {
byte[] buffer = new byte[4096];
FileInputStream fis = new FileInputStream(file);
for (Socket client : clients.values()) {
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.writeUTF(sender + " sent a file: " + file.getName());
int len;
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
}
fis.close();
}
}
}
```
Client.java
```
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
private static final String HOST = "localhost";
private static final int PORT = 12345;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
Socket socket = new Socket(HOST, PORT);
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF(name);
new Thread(() -> {
try {
while (true) {
String message = in.readUTF();
System.out.println(message);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}).start();
while (true) {
String message = scanner.nextLine();
if (message.startsWith("/private")) {
String[] tokens = message.split("\\s+", 3);
String target = tokens[1];
String text = tokens[2];
out.writeUTF("/private " + target + " " + text);
} else if (message.startsWith("/file")) {
String[] tokens = message.split("\\s+", 2);
String filename = tokens[1];
File file = new File(filename);
if (!file.exists()) {
System.out.println("Error: " + filename + " not found");
} else {
out.writeUTF("/file " + filename);
byte[] buffer = new byte[4096];
FileInputStream fis = new FileInputStream(file);
int len;
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
fis.close();
}
} else {
out.writeUTF(message);
}
}
}
}
```
在运行程序之前,需要先在命令行中进入到Server.java和Client.java所在的目录,然后依次编译和运行Server.java和多个Client.java。在运行Client.java时,需要输入用户名并按回车键进入聊天室。可以使用命令“/private target message”发送私聊消息,使用命令“/file filename”发送文件。
使用gui界面的java网络聊天室代码
以下是一个简单的基于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.Socket;
public class ChatClient extends JFrame {
private JTextArea chatArea;
private JTextField messageField;
private PrintWriter writer;
private BufferedReader reader;
public ChatClient() {
setTitle("Chat Client");
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) {
sendMessage();
}
});
add(messageField, BorderLayout.SOUTH);
setVisible(true);
connectToServer();
}
private void connectToServer() {
try {
Socket socket = new Socket("localhost", 5000);
writer = new PrintWriter(socket.getOutputStream(), true);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
new Thread(new Runnable() {
@Override
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
chatArea.append(message + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage() {
String message = messageField.getText();
writer.println(message);
messageField.setText("");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ChatClient();
}
});
}
}
```
这是一个简单的聊天客户端,它通过在本地主机上的端口5000连接到聊天服务器。当用户在文本框中输入消息并按下回车键时,消息将发送到服务器并显示在聊天区域中。聊天服务器的代码将在另一个类中实现。
阅读全文