下面是一個簡單的使用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連接到指定的服務器和端口,然后創建輸入輸出流進行消息的發送和接收。在主線程中,通過讀取用戶的輸入并發送到服務器。另外,在單獨的線程中,通過不斷地讀取輸入流來接收服務器發送的消息,并在控制臺進行輸出。