连接失败后socketchannel重新连接

时间:2014-08-20 18:03:31

标签: java multithreading sockets selector channel

您好我有一个运行实现方法的线程,这个线程(客户端)通过我的服务器管理通信,我想知道如何管理,以防它因连接问题而失败以及如何重新连接。我所做的就是你看到下面我添加了一个在连接失败时触发的监听器,我只是再次启动线程,isue或者spooky部分只是读取选项在重新连接后升级而且我不能通过套接字写任何东西可能是因为套接字发布不好,有什么帮助吗?谢谢

@Override
public void run() {
    try {

        selector = Selector.open();

        mSocketChannel = SocketChannel.open();
        mSocketChannel.configureBlocking(false);

        mSocketChannel.connect(new InetSocketAddress(mIpAddress, mPort));



        while(!mSocketChannel.finishConnect());

        mSocketChannel.register(selector,
                SelectionKey.OP_READ | SelectionKey.OP_WRITE);


        while (!stop) {

            int readyChannels = selector.select();

            if (readyChannels == 0)
                continue;

            //Log.i("selected","selected channels: "+readyChannels);
            Set<SelectionKey> selectedKeys = selector.selectedKeys();


            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

            while (keyIterator.hasNext()) {

                SelectionKey selectedKey = keyIterator.next();

                keyIterator.remove();

                if(!selectedKey.isValid()){
                    continue;
                }


                if (selectedKey.isAcceptable()) {

                } else if (selectedKey.isConnectable()) {

                } else if (selectedKey.isReadable()) {
                    read(selectedKey);

                } else if (selectedKey.isWritable()) {
                    write(selectedKey);
                }



            }


        }

        mSocketChannel.close();
        selector.close();


    } catch (IOException e) {
        try {
            mSocketChannel.close();
            selector.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if(mListener!=null)
            mListener.onScocketClosed();
        e.printStackTrace();

    }

0 个答案:

没有答案