簡體   English   中英

套接字總是超時使用Android庫

[英]Socket always time out with Android Libraries

即使在服務器(Java Server)上使用之前調用的ServerSocket.Accpet(),Android中的套接字也不會連接,來自客戶端(Android設備)的連接已接收並被接受,但客戶端永遠不會知道並保持超時。

這是服務器代碼,它在iOS上使用CocoaAsync庫並在開放端口上運行,並且在客戶端嘗試連接時打印“從...接受的套接字”,因此其連接和請求處理程序只是一個處理每個讀取的類。客戶端,在接受一個之后,它將再次循環並在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方面:

在manifest <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個庫的解決方案,稍后會發布

這是我用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);
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM