套接字始终在Android库中超时

时间:2018-06-23 06:16:37

标签: java android sockets socket.io androidasync-koush

即使在之前调用过ServerSocket.Accpet()的服务器(Java Server)上,Android的套接字也不会连接,并且已经接收并接受了来自客户端(Android设备)的连接,但是客户端永远不会知道并保持超时。

这是在服务器上使用CocoaAsync库在iOS上运行的代码 并在“开放端口”上运行,并且在客户端尝试连接时会显示“接受来自..的套接字”,因此其连接和请求处理程序只是一个类,用于处理来自每个客户端的读数,接受一个客户端之后,它将再次循环并等待在serverSocket.Accpet()上用于另一个客户端:

ServerSocket serverSocket = null;
    Socket socket = null;
    serverSocket = new ServerSocket(PORT);
    logger.info("started socket server on 127.0.0.1:" + PORT);
    while (true) {
        try {
            logger.info("waiting to receive connection ...");
            socket = serverSocket.accept();
            logger.info("socket accepted from " + socket.getInetAddress().getHostAddress());
        } catch (IOException e) {
            System.out.println("I/O error: " + e);
        }
        // new thread for a client
        RequestHandler t = new RequestHandler(socket);
        t.start();
    }

Android Side:

清单<uses-permission android:name="android.permission.INTERNET" />

使用Socket-io可以保持打印超时,连接错误,重新连接,...

    IO.Options options = new IO.Options();
    options.forceNew = true;
    options.transports = new String[]{WebSocket.NAME};


    try {
        socket = IO.socket(IP,options); //ip with port
        socket.connect();
        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                Utils.Log("Socket EVENT_CONNECT", API.class);
            }

        }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

            @Override
            public void call(Object... args) {
                Utils.Log("Socket EVENT_DISCONNECT", API.class);
            }

        }).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Utils.Log("Socket EVENT_CONNECT_ERROR", API.class);

            }
        }).on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Utils.Log("Socket EVENT_CONNECT_TIMEOUT", API.class);
            }
        }).on(Socket.EVENT_RECONNECT_ERROR, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        Utils.Log("Socket EVENT_RECONNECT_ERROR", API.class);
                    }
                })
        .on(Socket.EVENT_RECONNECT_FAILED, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Utils.Log("Socket EVENT_RECONNECT_FAILED", API.class);
            }
        }).on(Socket.EVENT_RECONNECTING, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Utils.Log("Socket EVENT_RECONNECTING", API.class);
            }
        }).on(Socket.EVENT_CONNECT_TIMEOUT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Utils.Log("Socket EVENT_CONNECT_TIMEOUT", API.class);
            }
        }).on(Socket.EVENT_MESSAGE, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Utils.Log("Socket EVENT_MESSAGE", API.class);
            }
        });
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

也使用AsyncAndroid超时,

AsyncHttpClient.getDefaultInstance().websocket(IP, "my-protocol", new AsyncHttpClient.WebSocketConnectCallback() {
        @Override
        public void onCompleted(Exception ex, WebSocket webSocket) {
            if (ex != null) {
                ex.printStackTrace();
                return;
            }
            webSocket.setEndCallback(new CompletedCallback() {
                @Override
                public void onCompleted(Exception ex) {
                    Utils.Log("Socket EndCallback", API.class);
                }
            });
            webSocket.setClosedCallback(new CompletedCallback() {
                @Override
                public void onCompleted(Exception ex) {
                    Utils.Log("Socket ClosedCallback", API.class);
                }
            });
            webSocket.setStringCallback(new WebSocket.StringCallback() {
                public void onStringAvailable(String s) {
                    Utils.Log("Socket setStringCallback", API.class);
                }
            });
            webSocket.setDataCallback(new DataCallback() {
                public void onDataAvailable(DataEmitter emitter, ByteBufferList byteBufferList) {
                    Utils.Log("Socket DataCallback", API.class);
                    byteBufferList.recycle();
                }
            });
        }
    });

,尝试了rxWebSocket,OkSocket,nv-websocket-client和其他一些具有相同结果的库 请记住,我可以使用Java.net简单套接字连接到服务器,并且它也可以与iOS一起使用。

在Android 8.1设备和仿真器上进行测试 在此先感谢。

更新:我想出了2个解决方案和2个库,并将在以后发布它们

1 个答案:

答案 0 :(得分:0)

这是我使用AsyncAndroid编写的代码,其中server,currentSocket,isConnected,isConnecting,sessionReloaded(您可能不需要它)是静态变量以发送请求,如果套接字是,则只需调用connectSocket(..)。连接后,将返回“ currentSocket”变量,以便可以对其进行写入,并在DataCallBack处处理读取过程,或者它将请求或您要写入套接字的任何内容添加到pendingList中,然后尝试进行连接,然后将所有挂起的内容写入。 (在我的情况下,连接后要写的第一件事是会话,因此您可能会忽略此模式,并且您可能有自己的政策,即将请求卡在(挂起)连接套接字后面以执行所需的操作,这就是我所使用的模式使用,但除此之外,这是很常见的事情

public static void connectSocket(onSocketConnectionListener listener) {
    if (server == null) {
        server = new AsyncServer();
    }
    if (server.isRunning()) {
        if (listener != null)
            listener.connected(currentSocket);
        return;
    }
    ConnectCallback socketCallBack = new ConnectCallback() {
        @Override
        public void onConnectCompleted(Exception ex, AsyncSocket socket) {
            isConnecting = false;
            if (ex != null) {
                server.stop();
                sessionReloaded = false;
                Utils.Log("Exception = " + ex.getCause() + " , Server Running State = " + server.isRunning(), API.class);
                A.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new android.os.Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                connectSocket(null);
                            }
                        }, 3000);
                    }
                });
                return;
            }
            Utils.Log("Server Running State = " + server.isRunning(), API.class);
            isConnected = true;
            currentSocket = socket;
            triggerConnections();
            socket.setDataCallback(new DataCallback() {
                @Override
                public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                    byte[] bytes = bb.getAllByteArray();
                    String[] content = Utils.splitJson(new String(bytes));
                    for (int i = 0; i < content.length; i++) {
                        Utils.Log("SocketDataReceived = " + content[i], API.class);
                        handleData(content[i]);
                    }
                    bb.recycle();
                }
            });
            socket.setClosedCallback(new CompletedCallback() {
                @Override
                public void onCompleted(Exception ex) {
                    if (ex != null) {
                        Utils.Log("Closed CallBack With Exception = " + ex.getCause(), API.class);
                    } else {
                        Utils.Log("Closed CallBack", API.class);
                    }
                    sessionReloaded = false;
                    isConnected = false;
                    server.stop();
                    triggerDisconnections();
                    A.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new android.os.Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    connectSocket(new onSocketConnectionListener() {
                                        @Override
                                        public void connected(AsyncSocket socket) {
                                        }
                                    });
                                    Utils.Log("Closed CallBack", API.class);
                                }
                            }, 3000);
                        }
                    });
                }
            });
            socket.setEndCallback(new CompletedCallback() {
                @Override
                public void onCompleted(Exception ex) {
                    if (ex != null) {
                        Utils.Log("End CallBack With Exception = " + ex.getCause(), API.class);
                    } else {
                        Utils.Log("End CallBack", API.class);
                    }
                    sessionReloaded = false;
                    isConnected = false;
                    server.stop();

                }
            });
            socket.setWriteableCallback(new WritableCallback() {
                @Override
                public void onWriteable() {
                    Utils.Log("Write CallBack", API.class);
                }
            });

            User user = MDatabase.getUser();
            String session = MDatabase.getSession();
            if (sessionNeedsReload()) {
                reloadSession(user.mobile, session);
            } else {
                doPendingRequests();
            }
        }
    };

    synchronized (isConnecting) {
        if (!isConnecting) {
            isConnecting = true;
            Utils.Log("Socket Connecting ...", API.class);
            server.connectSocket(IP, PORT, socketCallBack);
        }
    }
}