使用Java实现在局域网内通讯
时间: 2024-05-07 17:15:52 浏览: 128
Java局域网通信
要在局域网内实现通讯,可以使用Java的Socket编程。以下是一个简单的示例:
1. 服务端代码
```
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server started");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected: " + clientSocket);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received message from client: " + inputLine);
out.println("Server received your message: " + inputLine);
}
System.out.println("Client disconnected");
in.close();
out.close();
clientSocket.close();
}
}
}
```
2. 客户端代码
```
import java.net.*;
import java.io.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345);
System.out.println("Connected to server");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
String inputLine;
while ((inputLine = userInput.readLine()) != null) {
out.println(inputLine);
String response = in.readLine();
System.out.println("Received response from server: " + response);
}
in.close();
out.close();
userInput.close();
socket.close();
}
}
```
在这个示例中,服务端在12345端口上监听客户端连接。当有新的客户端连接时,服务端会创建一个新的线程来处理该客户端的请求。客户端连接到localhost上的12345端口,发送数据给服务端,然后等待服务端的响应。当客户端输入exit时,它会关闭连接并退出。
阅读全文