两个安卓设备用TCP互相连接例子
时间: 2024-03-15 19:45:37 浏览: 71
Android NDK tcp例子
5星 · 资源好评率100%
以下是两个 Android 设备之间使用 TCP 协议互相连接的示例代码:
在发送端的设备上:
```java
public class ClientThread implements Runnable {
private Socket socket;
private String serverIp;
private int serverPort;
public ClientThread(String serverIp, int serverPort) {
this.serverIp = serverIp;
this.serverPort = serverPort;
}
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIp);
socket = new Socket(serverAddr, serverPort);
// 发送数据
OutputStream outputStream = socket.getOutputStream();
String message = "Hello server!";
outputStream.write(message.getBytes());
// 接收数据
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int length = inputStream.read(buffer);
String receivedMessage = new String(buffer, 0, length);
Log.d("ClientThread", "Received message: " + receivedMessage);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 启动客户端线程
new Thread(new ClientThread("192.168.0.100", 12345)).start();
```
在接收端的设备上:
```java
public class ServerThread implements Runnable {
private ServerSocket serverSocket;
private int serverPort;
public ServerThread(int serverPort) {
this.serverPort = serverPort;
}
@Override
public void run() {
try {
serverSocket = new ServerSocket(serverPort);
while (true) {
Socket socket = serverSocket.accept();
// 接收数据
InputStream inputStream = socket.getInputStream();
byte[] buffer = new byte[1024];
int length = inputStream.read(buffer);
String receivedMessage = new String(buffer, 0, length);
Log.d("ServerThread", "Received message: " + receivedMessage);
// 发送数据
OutputStream outputStream = socket.getOutputStream();
String message = "Hello client!";
outputStream.write(message.getBytes());
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 启动服务器线程
new Thread(new ServerThread(12345)).start();
```
以上代码中,客户端线程向指定的服务器 IP 和端口发送数据,服务器线程监听指定的端口并接受客户端的连接请求,接收客户端发送的数据并发送响应数据。请将 `192.168.0.100` 替换为发送端设备的 IP 地址。
阅读全文