isConnected失败:ECONNREFUSED(拒绝连接)

时间:2016-05-28 14:30:47

标签: javascript android sockets connection wifi-direct

我尝试通过wifi-direct在手机之间传输数据,我的代码每次运行时都能很好地工作。但是,在我关闭客户端和服务器中的所有套接字并尝试再次连接套接字后,它给了我这个例外。此外,在我锁定服务器电话的屏幕并解锁后,我可以再次建立连接。有人熟悉套接字可以给我任何建议吗? 这不应该是关于错误的IP地址/端口权限吗?

客户电话代码



protected void onHandleIntent(Intent intent) {

        Context context = getApplicationContext();
        if (intent.getAction().equals(ACTION_SEND_FILE)) {
            if(!socket.isConnected())
            {
                String host = intent.getExtras().getString(
                        EXTRAS_GROUP_OWNER_ADDRESS);
                int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
                try {
                    socket.bind(null);
                    InetSocketAddress MyAddress = new InetSocketAddress(host, port);
                    socket.connect(MyAddress, SOCKET_TIMEOUT);
                }
                catch(IOException e) {
                    Log.e(TAG, e.getMessage());
                }
            }
                try{
				     /*returns an output stream to write data into this socket*/
                    OutputStream stream = socket.getOutputStream();
                    String count = String.valueOf(_count);
                    stream.write(count.getBytes());                  
            } catch (IOException e) {
                Log.e(TAG, e.getMessage());
            } finally {
                if (socket != null) {

                    if (socket.isConnected()) {

                        try {
                            InputStream is = socket.getInputStream();
                            socket.shutdownOutput(); // Sends the 'FIN' on the network
                            while (is.read() >= 0) ; // "read()" returns '-1' when the 'FIN' is reached
                            socket.close();
                        }

                        catch (IOException e) {
                            // Give up
                            e.printStackTrace();
                        }

                    }
                }
            }

        }
    }




服务器电话的代码



protected String doInBackground(Void... params) {
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            Socket client = serverSocket.accept();
            InputStream inputstream = client.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i;
            while ((i = inputstream.read()) != -1) {
                baos.write(i);
            }
            String str = baos.toString();
            client.shutdownOutput(); // Sends the 'FIN' on the network
            while (inputstream.read() >= 0) ; // "read()" returns '-1' when the 'FIN' is reached
            client.close(); // Now we can close the Socket
            serverSocket.close();
            return str;

        } catch (IOException e) {
            return null;
        }
    }




0 个答案:

没有答案