写一个安卓10的java层阻塞socket通信服务端和客户端
时间: 2023-11-06 09:08:28 浏览: 198
Android环境下Socket编程,服务器端和客户端通讯
5星 · 资源好评率100%
好的,以下是一个简单的安卓10的Java层阻塞socket通信服务端和客户端的实现代码:
服务端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(12345); // 监听端口号为12345
System.out.println("Server started, listening on port 12345...");
while (true) {
Socket socket = serverSocket.accept(); // 阻塞等待客户端连接
System.out.println("Client connected: " + socket.getRemoteSocketAddress());
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) { // 阻塞等待客户端数据
String msg = new String(buffer, 0, len);
System.out.println("Received from client: " + msg);
outputStream.write(("Server received: " + msg).getBytes()); // 发送数据给客户端
outputStream.flush();
}
socket.close(); // 关闭连接
System.out.println("Client disconnected: " + socket.getRemoteSocketAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
客户端代码:
```java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345); // 连接到本地的12345端口
System.out.println("Connected to server: " + socket.getRemoteSocketAddress());
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
String msg = "Hello, server!";
outputStream.write(msg.getBytes()); // 发送数据给服务端
outputStream.flush();
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer); // 阻塞等待服务端数据
String responseMsg = new String(buffer, 0, len);
System.out.println("Received from server: " + responseMsg);
socket.close(); // 关闭连接
System.out.println("Disconnected from server.");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这里实现的是简单的“Hello world”级别的通信,你可以根据实际需求进行修改和扩展。
阅读全文