z***@163.com
z***@163.com
  • 发布:2019-03-22 09:10
  • 更新:2022-05-16 18:59
  • 阅读:1344

uni-app里native方式启动socket,runOnUiThread、thread 都报NetworkOnMainThreadException

分类:uni-app
onShow: function() {  
            var App = plus.android.runtimeMainActivity();             
            var Thread = plus.ios.importClass("java.lang.Thread");  
            var SocketChannel = plus.android.importClass("java.nio.channels.SocketChannel");  
            var InetSocketAddress = plus.android.importClass("java.net.InetSocketAddress");  
            var ServerSocketChannel = plus.android.importClass("java.nio.channels.ServerSocketChannel");  
            var ByteBuffer = plus.android.importClass("java.nio.ByteBuffer");  
            var Runnable = plus.android.implements("java.lang.Runnable", {  
                "run": function() {  
                    try {  
                        while (true) {  
                            var serverSocketChannel = ServerSocketChannel.open();  
                            serverSocketChannel.socket().bind(new InetSocketAddress(10086));  
                            var socketChannel = serverSocketChannel.accept();  
                            var buf = ByteBuffer.allocate(128);  
                            buf.clear();  
                            var len = socketChannel.read(buf);  
                            var count = 0;  
                            while (len > 0) {  
                                count  = len;  
                                buf.flip();  
                                while (buf.position() < buf.limit()) {  
                                    console.log(buf.get());  
                                }  
                                //#todo 未读满缓存,不一定读完了  
                                if (buf.limit() < buf.capacity()) {  
                                    break;  
                                }  
                                buf.clear();  
                                len = socketChannel.read(buf);  
                            }  
                            buf.clear();  
                            var sendStr = '接收完成';  
                            buf = ByteBuffer.wrap(sendStr.toString().getBytes("UTF-8"));  
                            socketChannel.write(buf);  
                            socketChannel.close();  
                        }  
                    } catch (e) {  
                        console.log('>>>>>>>>>>>>'   JSON.stringify(e));  
                    }  
                }  
            });  
            //方式1启动线程    
            //App.runOnUiThread(Runnable);  
            //2  
            var th = new Thread(Runnable);  
            th.start();  
        },

提示异常:
android.os.NetworkOnMainThreadException;at java.net.ServerSocket.accept

2019-03-22 09:10 负责人:无 分享
已邀请:
MonikaChen

MonikaChen

我也遇到类似问题,楼主解决了吗?

g***@qq.com

g***@qq.com

同问

要回复问题请先登录注册