利用多线程、网络编程设计一个聊天程序。要求通过监听指定的端口号、目标IP地址和目标端口号,实现消息的发送和接收功能,并把聊天内容显示出来。 Java 实现
时间: 2024-02-05 16:11:03 浏览: 127
以下是一个简单的Java聊天程序的实现,它使用多线程和网络编程:
```java
import java.io.*;
import java.net.*;
public class ChatServer implements Runnable {
private ServerSocket serverSocket;
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
private Thread thread;
public ChatServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
System.out.println("Chat server started on port " + port);
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void run() {
try {
clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received message: " + inputLine);
out.println(inputLine);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
int portNumber = 1234;
try {
ChatServer server = new ChatServer(portNumber);
server.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
public class ChatClient {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
public ChatClient(String address, int port) throws IOException {
socket = new Socket(address, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
public void sendMessage(String message) {
out.println(message);
}
public String receiveMessage() throws IOException {
return in.readLine();
}
public void close() throws IOException {
out.close();
in.close();
socket.close();
}
public static void main(String[] args) {
String serverAddress = "localhost";
int portNumber = 1234;
try {
ChatClient client = new ChatClient(serverAddress, portNumber);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String inputLine;
while ((inputLine = reader.readLine()) != null) {
client.sendMessage(inputLine);
System.out.println("Received message: " + client.receiveMessage());
}
reader.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
在这个聊天程序中,ChatServer类监听指定的端口号,接收来自客户端的消息,并将消息发送回客户端。ChatClient类连接到服务器并发送消息,然后接收服务器的响应并将其显示在控制台上。
要运行聊天程序,可以先启动ChatServer,然后启动一个或多个ChatClient实例。当客户端发送消息时,服务器将在控制台上显示接收到的消息。当服务器发送消息时,客户端将在控制台上显示接收到的消息。
阅读全文