套接字未在Oreo上打开

时间:2018-07-01 20:54:18

标签: java android sockets android-8.0-oreo

我正在使用Oreo 8.0的Samsung Galaxy S7上运行此代码,并且套接字未打开,当我尝试连接时收到“连接被拒绝”。相同的代码在带有棉花糖6.0.1的三星Galaxy S5上可以正常工作。奥利奥(Oreo)的套接字API是否有变化?

Handler handler = new Handler();
ServerThread serverThread = new ServerThread(handler);
Thread thread = new Thread(serverThread);
thread.start();

还有ServerThread类:

public class ServerThread implements Runnable {

private ServerSocket serverSocket;
private Socket client;
private DataInputStream dataInputStream;
private Handler handler;

public ServerThread(Handler handler) {
    this.handler = handler;
}

@Override
public void run() {
    try {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Log.d("app", "listening...");
            }
        });
        serverSocket = new ServerSocket();
        serverSocket.setReuseAddress(true);
        serverSocket.bind(new InetSocketAddress(5000));
        client = serverSocket.accept();
        handler.post(new Runnable() {
            @Override
            public void run() {
                Log.d("app", "connected");
            }
        });
        dataInputStream = new DataInputStream(client.getInputStream());
        boolean done = false;
        while (!done) {
            try {
                byte messageType = dataInputStream.readByte();
                Log.d("app", "read byte " + messageType);
                switch (messageType) {
                    // do something here, at some point I set done = true
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        dataInputStream.close();
        serverSocket.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

0 个答案:

没有答案