用Java编写聊天功能的代码
时间: 2024-05-11 18:15:31 浏览: 52
我很乐意回答你的问题。以下是一个简单的使用Java编写聊天功能的示例代码:
```
import java.net.*;
import java.io.*;
public class ChatServer {
private ServerSocket server = null;
private Socket client = null;
private BufferedReader in = null;
private PrintWriter out = null;
public ChatServer(int port) {
try {
server = new ServerSocket(port);
System.out.println("服务器启动成功,等待客户端连接...");
client = server.accept();
System.out.println("客户端连接成功!");
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
String msg = "";
try {
while ((msg = in.readLine()) != null) {
System.out.println("客户端:" + msg);
out.println("服务器:"+ msg);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
client.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ChatServer server = new ChatServer(8888);
server.start();
}
}
```
这个代码演示了如何使用Java的Socket API来创建一个简单的服务器,使用BufferedReader和PrintWriter实现客户端与服务器之间的消息传输。你可以根据自己的需要对代码进行修改和扩展。
阅读全文