简体   繁体   English

Android,Java,套接字,确定远程主机断开连接

[英]Android,Java,socket, determine remote host disconnect

I'm trying to code a TCP client in android java. 我正在尝试在android java中编码TCP客户端。 Most works fine. 大多数都能正常工作。 But i have one issue. 但是我有一个问题。 If the socket is connected and the remeote host shuts down or the network goes down or something else, the socket.getinputstream keeps blocking. 如果已连接套接字,并且风味果主机关闭或网络中断或其他原因,则socket.getinputstream会继续阻塞。

I don't know if the socket is still connected. 我不知道套接字是否仍然连接。 I code in objective-c too and in objective-c i get an event that the socket forcefully shuts down and i can try to reconnect. 我也在Objective-C和Objective-C中进行编码,但我遇到了套接字被强制关闭的事件,我可以尝试重新连接。 So on objective c the socket tracks the state. 因此,在目标c上,套接字跟踪状态。

In java the socket and the inputstream is still connected or blocked even the socket is down. 在Java中,即使套接字已关闭,套接字和inputstream仍被连接或阻塞。 How can i check if the socket is still connected? 我如何检查插座是否仍然连接?

        @Override
        protected Void doInBackground(String... params) {
        try {
                    String host = params[0];
                    int port = Integer.parseInt(params[1]);
                    SocketAddress sockaddr = new InetSocketAddress(host, port);
                    Socket socket = new Socket();
                    socket.connect(sockaddr,5000);
                    socket.setSoTimeout(7000);

                    out = new PrintWriter(socket.getOutputStream(), true);
                    mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    while (mRun) {
                        try {
             ----->         mServerMessage = mBufferIn.readLine();
                        }catch (Exception e){
                            Log.d("my","hier3" + e.getMessage());
                        }
                        if (mServerMessage.trim() != null) {

                                sender.messageReceived(s2);

                             }else{

                            }

                        }

                    }

                } catch (UnknownHostException e

) {

The question of how to detect if the remote peer/socket has closed the connection has been answered here as well as here . 此处此处回答了如何检测远程对等方/套接字是否已关闭连接的 问题 Basically, the answers suggest that you attempt to read from the socket, and then observe what happens ( read() returns -1 , or readLine() returns null or your read methods raise EOFException . 基本上,答案表明您尝试从套接字读取,然后观察会发生什么情况( read()返回-1 ,或者readLine()返回null或您的read方法引发EOFException

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

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