安卓 监听socket消息 指令
时间: 2023-08-07 13:09:08 浏览: 41
在 Android 中监听 Socket 消息,可以使用 Java 中的 Socket 类和线程来实现。下面是一个示例代码:
```java
public class SocketThread extends Thread {
private Socket socket;
private BufferedReader in;
public SocketThread(Socket socket) {
this.socket = socket;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
while (!isInterrupted()) {
String message = in.readLine();
if (message != null) {
// 处理收到的消息
Log.d("SocketThread", "Received message: " + message);
} else {
break;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
在主线程中创建 Socket 并启动监听线程:
```java
try {
Socket socket = new Socket("localhost", 8888);
SocketThread socketThread = new SocketThread(socket);
socketThread.start();
} catch (IOException e) {
e.printStackTrace();
}
```
这里假设监听的是本机的 8888 端口,你需要根据实际情况修改。另外,你需要根据具体的需求来处理收到的消息。