简体   繁体   English

Android套接字连接问题

[英]Android socket connection issues

I am creating a chat application, which runs as a service. 我正在创建一个作为应用程序运行的聊天应用程序。 I connect to the chat server using a socket, and I declared a timeout using setSoTimeout . 我使用套接字连接到聊天服务器,并使用setSoTimeout声明了超时。

When a connection is idle, (for example when I am at home and connected to WiFi) I never face issues. 当连接处于空闲状态时(例如,当我在家中并连接到WiFi时),我再也不会遇到问题。 When I go outside, and my WiFi connection is lost, my phone switches to 3G. 当我出门在外且WiFi连接丢失时,手机将切换到3G。 The problem is that the socket stays connected without receiving any data. 问题在于套接字保持连接状态而没有接收任何数据。 (So the timeout exception isn't called.) < sometimes it connects after 30 mins, but this need to be reduced to at least a few seconds. (因此,不会调用超时异常。)<有时它在30分钟后连接,但这需要至少减少几秒钟。

I also tried to add a CONNECTIVITY_CHANGE broadcast detector in my AndroidManifest.xml, this also didn't work. 我还尝试在我的AndroidManifest.xml中添加CONNECTIVITY_CHANGE广播检测器,这也没有用。

See my socket connection below: 请参阅下面的我的套接字连接:

    socket = new Socket(proxy);
    SocketAddress socketAddress = new InetSocketAddress(HOST,
                PORT);
    socket.connect(socketAddress);
    if (socket.isConnected()) {
        socket.setSoTimeout(1020000); //Even when setting to 10000 makes no sense
        return true;
    } else {
        Log.w("WARNING", "Failed to connect to the server");
        return false;
    }

In the background there are also some loops running which checks the server for chatmessages, these loops triggers a reconnect when no data is received, but this didn't work too. 在后台还运行着一些循环,这些循环检查服务器上的聊天消息,当没有接收到任何数据时,这些循环会触发重新连接,但这也行不通。 (During reconnect, I set the socket to socket.close() and socket = null before connecting again.) (在重新连接期间,在再次连接之前,我将套接字设置为socket.close()并且socket = null 。)

So are there any ideas, maybe I need to use a different socket? 有什么想法,也许我需要使用其他插座? Or some other code to resolve this problem? 或其他一些代码来解决此问题? Thanks. 谢谢。

In such unexpected(as per application's perspective) network disconnection, the socket won't know it was disconnected. 在这种非预期的(从应用程序的角度来看)网络断开连接中,套接字不知道它已断开连接。 If this situation occurs, the only way is to try writing some data to the socket. 如果发生这种情况,唯一的方法是尝试将一些数据写入套接字。 When the socket is disconnected, writing data would throw IOExcpetion with message like Connection reset . 当套接字断开连接时,写入数据将引发IOExcpetion并显示诸如Connection reset消息。

You'd better implement a heartbeat method to detect the disconnection. 您最好实施心跳检测方法来检测断开连接。 A packet sent to server every 5~10 seconds would detect network disconnection speedy enough. 每5〜10秒发送到服务器的数据包将足够快地检测到网络断开连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM