prism 写一个通信模块
时间: 2023-08-10 18:05:38 浏览: 89
好的,这里我给您提供一个简单的通信模块的实现,使用了 Java 语言和 Socket 编程。
1. 服务端代码:
```java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
// 创建 ServerSocket 对象并绑定端口号
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.err.println("Could not listen on port: 8888.");
System.exit(-1);
}
Socket clientSocket = null;
System.out.println("等待客户端连接...");
try {
// 等待客户端连接
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(-1);
}
System.out.println("客户端已连接!");
// 获取输入流和输出流
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// 读取客户端发送的消息并回复
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("客户端: " + inputLine);
out.println("服务端已接收到消息: " + inputLine);
if (inputLine.equals("exit"))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
```
2. 客户端代码:
```java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
// 创建 Socket 对象并连接服务器
socket = new Socket("localhost", 8888);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: localhost.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: localhost.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
// 发送消息到服务器并读取回复
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("服务端: " + in.readLine());
if (userInput.equals("exit"))
break;
}
out.close();
in.close();
stdIn.close();
socket.close();
}
}
```
这个通信模块的实现比较简单,它只能在本地运行,并且没有进行错误处理和安全性考虑。但是,它可以作为一个基础的 Socket 编程示例,帮助您更好地理解通信模块的工作原理。
阅读全文