当前位置: 首页>>代码示例>>Java>>正文


Java SocketChannel.close方法代码示例

本文整理汇总了Java中java.nio.channels.SocketChannel.close方法的典型用法代码示例。如果您正苦于以下问题:Java SocketChannel.close方法的具体用法?Java SocketChannel.close怎么用?Java SocketChannel.close使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.channels.SocketChannel的用法示例。


在下文中一共展示了SocketChannel.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: handle

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void handle(SelectionKey key) {
	SocketChannel channel = (SocketChannel) key.channel();
	if (key.isConnectable()) {
		try {
			if (channel.finishConnect()) {
				//connect finish
				this.logger.info("[Connecter] finish connect " + channel.getRemoteAddress().toString());
				IoWorker worker = this.workers.get(workersIndex);
				worker.dispatch(new JobBean(channel, this.chanToParam.get(channel)));
				workersIndex = (workersIndex + 1) % workers.size();
			}
		} catch (IOException e) {
			this.logger.info("[Connecter] finish connect error : " + e.toString());
			ClientParam clientParam = this.chanToParam.get(channel);
			if (clientParam.getOnConnectError() != null) {
				clientParam.getOnConnectError().onConnectError(e);
			}
			this.chanToParam.remove(channel);
			try {
				channel.close();
			} catch (IOException e1) {
				// already close
			}
		}
	}
}
 
开发者ID:luohaha,项目名称:LightComm4J,代码行数:27,代码来源:Connector.java

示例2: readData

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void readData() throws Exception {
    buff.clear();
    SocketChannel sc = (SocketChannel) sk.channel();
    int count = -1;
    while ((count = sc.read(buff)) > 0) {
        // TODO - in the future pass this to a "listener" which will do something useful with this buffer
        buff.clear();
    }

    if (count < 0) {
        sc.close();
    } else {
        sk.interestOps(sk.interestOps() | SelectionKey.OP_READ);
    }

    sel.wakeup();

}
 
开发者ID:fast-data-transfer,项目名称:fdt,代码行数:19,代码来源:JIperfServer.java

示例3: openConnection

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
/**
 * out node try to connect
 *
 * @param node
 */
public void openConnection(Node node) {

    SocketChannel channel = null;
    try {
        channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.socket().setReuseAddress(true);
        InetSocketAddress socketAddress = new InetSocketAddress(node.getIp(), node.getPort());
        channel.connect(socketAddress);
        PendingConnect data = new PendingConnect(channel, node);
        SelectionKey key = channel.register(selector, SelectionKey.OP_CONNECT);
        key.attach(data);
        selector.wakeup();
    } catch (IOException e) {
        e.printStackTrace();
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        node.destroy();
    }
}
 
开发者ID:nuls-io,项目名称:nuls,代码行数:31,代码来源:ConnectionManager.java

示例4: read

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void read(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    int bytesRead;
    try {
        bytesRead = channel.read(buffer);
    } catch (IOException exception) {
        key.cancel();
        channel.close();
        if (this.rconSessions.contains(channel)) {
            this.rconSessions.remove(channel);
        }
        if (this.sendQueues.containsKey(channel)) {
            this.sendQueues.remove(channel);
        }
        return;
    }

    if (bytesRead == -1) {
        key.cancel();
        channel.close();
        if (this.rconSessions.contains(channel)) {
            this.rconSessions.remove(channel);
        }
        if (this.sendQueues.containsKey(channel)) {
            this.sendQueues.remove(channel);
        }
        return;
    }

    buffer.flip();
    this.handle(channel, new RCONPacket(buffer));
}
 
开发者ID:JupiterDevelopmentTeam,项目名称:Jupiter,代码行数:36,代码来源:RCONServer.java

示例5: testConnectCallback

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
@Test
public void testConnectCallback() throws IOException {
    eventLoop.registerAccept(acceptSocket, serverHandler);

    SocketChannel clientSocket = SocketChannel.open();
    clientSocket.configureBlocking(false);
    boolean connected = clientSocket.connect(
            new InetSocketAddress(InetAddress.getLocalHost(), serverPort));
    assertFalse(connected);
    assertTrue(clientSocket.isConnectionPending());
    eventLoop.registerConnect(clientSocket, serverHandler);
    // registering it for reading as well is not permitted: causes problems on Linux
    try {
        eventLoop.registerRead(clientSocket, serverHandler);
        fail("expected exception");
    } catch (AssertionError e) {}

    // The event loop will trigger the accept callback
    assertNull(serverHandler.client);
    eventLoop.runOnce();
    assertNotNull(serverHandler.client);
    assertTrue(clientSocket.isConnectionPending());

    // The event loop will also have triggered the connect callback
    assertTrue(serverHandler.connected);
    connected = clientSocket.finishConnect();
    assertTrue(connected);
    assertTrue(clientSocket.isConnected());

    // Registering some other handler in response to the connect event should work
    eventLoop.registerRead(clientSocket, new TestHandler());

    clientSocket.close();
}
 
开发者ID:s-store,项目名称:s-store,代码行数:35,代码来源:NIOEventLoopTest.java

示例6: closeConnection

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static void closeConnection(SocketChannel connection) throws InterruptedException, IOException {
    synchronized (m_executors) {
        ExecutorPair p = m_executors.remove(connection);
        assert(p != null);
        p.shutdown();
    }
    connection.close();
}
 
开发者ID:s-store,项目名称:sstore-soft,代码行数:9,代码来源:ConnectionUtil.java

示例7: handleInput

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
/** 对接收到的key进行处理
 *@description 相关说明
 *@time 创建时间:2017年7月17日下午2:55:56
 *@param key
 *@throws IOException
 *@author dzn
 */
private void handleInput(SelectionKey key) throws IOException{
    if(key.isValid()){
       SocketChannel sc = (SocketChannel)key.channel();
       if(key.isConnectable()){
           if(sc.finishConnect()){
               sc.register(this.selector, SelectionKey.OP_READ);
               this.doWrite(sc);
           }else{
               System.exit(1);//连接失败,进程退出
           }
       }
       
       if(key.isReadable()){
           ByteBuffer bb = ByteBuffer.allocate(1024);
           int readBytes = sc.read(bb);
           if(readBytes > 0){
               bb.flip();
               byte[] bytes = new byte[bb.remaining()];
               bb.get(bytes);
               String body = new String(bytes, "UTF-8");
               System.out.println("Now is " + body);
               this.stop = true;
           }else if(readBytes < 0){
               key.cancel();
               sc.close();
           }else{
               ;// 读到0字节,忽略
           }
       }
    }
}
 
开发者ID:SnailFastGo,项目名称:netty_op,代码行数:39,代码来源:TimeClientHandler.java

示例8: write

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
private void write(SelectionKey key) throws IOException {
    SocketChannel channel = (SocketChannel) key.channel();

    synchronized (this.sendQueues) {
        List<RCONPacket> queue = this.sendQueues.get(channel);

        ByteBuffer buffer = queue.get(0).toBuffer();
        try {
            channel.write(buffer);
            queue.remove(0);
        } catch (IOException exception) {
            key.cancel();
            channel.close();
            if (this.rconSessions.contains(channel)) {
                this.rconSessions.remove(channel);
            }
            if (this.sendQueues.containsKey(channel)) {
                this.sendQueues.remove(channel);
            }
            return;
        }

        if (queue.isEmpty()) {
            this.sendQueues.remove(channel);
        }

        key.interestOps(SelectionKey.OP_READ);
    }
}
 
开发者ID:JupiterDevelopmentTeam,项目名称:Jupiter,代码行数:30,代码来源:RCONServer.java

示例9: switchToUSB

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static boolean switchToUSB(String deviceSerial) {
    SocketChannel channel = openAdbConnection();
    try {
        if (send(channel, SELECT_DEVICE.replace("sn", deviceSerial))) {
            return send(channel, SWITCH_TO_USB);
        }
    } finally {
        try {
            channel.close();
        } catch (IOException ex) {
        }
    }
    return false;
}
 
开发者ID:NBANDROIDTEAM,项目名称:NBANDROID-V2,代码行数:15,代码来源:NbAndroidAdbHelper.java

示例10: close

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
@Override
public void close(SelectionKey key) {
    key.cancel();
    SocketChannel sc = (SocketChannel) key.channel();
    try {
        sc.close();
        logger.info("close client success");
    } catch (IOException e) {
        logger.error("close client error", e);
    }
}
 
开发者ID:xiaoma20082008,项目名称:mysql-protocol,代码行数:12,代码来源:MySQLConnection.java

示例11: readFromKey

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static void readFromKey(
        SelectionKey key, ByteBuffer readBuffer,
        ByteArrayOutputStream bos, Consumer<byte[]> packetProcessor
) throws IOException {

    SocketChannel socketChannel = (SocketChannel) key.channel();

    // Attempt to read off the channel
    int numRead;
    try {
        numRead = socketChannel.read(readBuffer);
    } catch (IOException e) {
        LOG.error("", e);
        key.cancel();
        socketChannel.close();
        return;
    }

    if (numRead == -1) {
        // Remote entity shut the socket down cleanly. Do the
        // same from our end and cancel the channel.
        key.channel().close();
        key.cancel();
    } else {
        processReadBuffer(readBuffer, bos, packetProcessor);
    }

}
 
开发者ID:yiding-he,项目名称:java-nio-test,代码行数:29,代码来源:ByteBufferEncoder.java

示例12: terminate

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
void terminate() {
	SocketChannel socketChannel = _socketChannel;
	try {
		if (socketChannel != null) {
			socketChannel.close();
		}
	} catch (Exception e) {
		XulLog.e(TAG, e);
	}
	clear();
}
 
开发者ID:starcor-company,项目名称:starcor.xul,代码行数:12,代码来源:XulHttpServer.java

示例13: connectEthernet

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public static boolean connectEthernet(String ipPort) {
    SocketChannel channel = openAdbConnection();
    try {
        return send(channel, CONNECT_TCP_ALL + ipPort);
    } finally {
        try {
            channel.close();
        } catch (IOException ex) {
        }
    }

}
 
开发者ID:NBANDROIDTEAM,项目名称:NBANDROID-V2,代码行数:13,代码来源:NbAndroidAdbHelper.java

示例14: run

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public void run() {
    SocketChannel sChannel = null;
    try {
        /*
         * For future unwary socket programmers: although connect 'blocks' it
         * does not require an accept on the server side to return. Therefore
         * you can not assume that all the sockets are connected at the end of
         * this for loop.
         */
        sChannel = SocketChannel.open();
        sChannel.connect(new InetSocketAddress(host,port));
        // Construct a connection request
        ConnectRequest conReq = new ConnectRequest(0, 0,
                10000, 0, "password".getBytes());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
        boa.writeInt(-1, "len");
        conReq.serialize(boa, "connect");
        baos.close();
        ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
        bb.putInt(bb.capacity() - 4);
        bb.rewind();

        /* Send a connect request. Any socket that has been closed (or at least
         * not added to the cnxn list on the server) will not have any bytes to
         * read and get an eof.
         *
         *  The trick here was finding a call that caused the server to put
         *  bytes in the input stream without closing the cnxn. None of
         *  the four letter commands do that, so we actually try to create
         *  a session which should send us something back, while maintaining
         *  the connection.
         */

        int eof = sChannel.write(bb);
        // If the socket times out, we count that as Assert.failed -
        // the server should respond within 10s
        sChannel.socket().setSoTimeout(10000);
        if (!sChannel.socket().isClosed()){
            eof = sChannel.socket().getInputStream().read();
            if (eof != -1) {
                numConnected.incrementAndGet();
            }
        }
    }
    catch (IOException io) {
        // "Connection reset by peer"
    }
    finally {
        if (sChannel != null) {
            try {
                sChannel.close();
            }
            catch (Exception e) {
            }
        }
    }
}
 
开发者ID:l294265421,项目名称:ZooKeeper,代码行数:59,代码来源:MaxCnxnsTest.java

示例15: doWork

import java.nio.channels.SocketChannel; //导入方法依赖的package包/类
public void doWork() throws Exception {
    for (; ; ) {
        //TODO, stop the server (this loop and the executor) if there are no more connected sockets
        while (sel.select() > 0)
            ;
        Iterator it = sel.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = (SelectionKey) it.next();

            if (sk.isAcceptable()) {
                ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
                SocketChannel sc = ssc.accept();
                if (!sshMode) {// standalone mode
                    sc.configureBlocking(false);
                    sc.register(sel, SelectionKey.OP_READ);
                } else {// SSH mode
                    if (allowedIP != null && !allowedIP.equals(sc.socket().getInetAddress().getHostAddress())) {
                        // just the IP passed on secured SSH control connection is allowed to connect
                        System.err.println(" [" + allowedIP + "] does not match " + sc.socket().getInetAddress().getHostAddress());
                        sc.close();
                    } else {// allowed connection
                        sc.configureBlocking(false);
                        sc.register(sel, SelectionKey.OP_READ);
                        if (--connectionNo == 0) {
                            // stop listening for other connection
                            this.ssc.keyFor(sel).cancel();
                            this.ssc.close();
                        }
                    }
                }
            } else if (sk.isReadable()) {
                sk.interestOps(sk.interestOps() & ~SelectionKey.OP_READ);
                executor.execute(new ReaderTask(sk));
            }

            it.remove();
        }
    }


}
 
开发者ID:fast-data-transfer,项目名称:fdt,代码行数:42,代码来源:JIperfServer.java


注:本文中的java.nio.channels.SocketChannel.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。