Java

用java编写qq聊天程序

小云
144
2023-09-13 05:28:36
栏目: 编程语言

下面是一个简单的使用Java编写的QQ聊天程序的代码示例:

import java.io.*;
import java.net.*;
public class QQChatClient {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
public QQChatClient(String host, int port) {
try {
// 连接服务器
socket = new Socket(host, port);
System.out.println("成功连接到服务器");
// 创建输入输出流
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
// 启动接收消息线程
new Thread(new MessageReceiver()).start();
// 读取用户输入并发送消息
BufferedReader userInputReader = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = userInputReader.readLine()) != null) {
writer.println(userInput);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null) {
socket.close();
}
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
QQChatClient chatClient = new QQChatClient("localhost", 8888);
}
class MessageReceiver implements Runnable {
@Override
public void run() {
try {
String message;
while ((message = reader.readLine()) != null) {
System.out.println("收到消息:" + message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

该程序使用Socket连接到指定的服务器和端口,然后创建输入输出流进行消息的发送和接收。在主线程中,通过读取用户的输入并发送到服务器。另外,在单独的线程中,通过不断地读取输入流来接收服务器发送的消息,并在控制台进行输出。

0
看了该问题的人还看了