3

即使在服务器(Java 服务器)上使用 ServerSocket.Accpet() 调用之前,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();
    }

安卓端:

在清单上<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 个解决方案,稍后将发布它们

4

1 回答 1

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);
        }
    }
}
于 2018-07-06T07:26:30.843 回答