當前位置: 首頁>>代碼示例>>Java>>正文


Java SocketChannel.configureBlocking方法代碼示例

本文整理匯總了Java中java.nio.channels.SocketChannel.configureBlocking方法的典型用法代碼示例。如果您正苦於以下問題:Java SocketChannel.configureBlocking方法的具體用法?Java SocketChannel.configureBlocking怎麽用?Java SocketChannel.configureBlocking使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.nio.channels.SocketChannel的用法示例。


在下文中一共展示了SocketChannel.configureBlocking方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: SocketConnection

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public SocketConnection(SocketChannel socket, MessageSerializer streamSerializer, StatefulSerializer<T> messageSerializer) {
    this.socket = socket;
    try {
        // NOTE: we use non-blocking IO as there is no reliable way when using blocking IO to shutdown reads while
        // keeping writes active. For example, Socket.shutdownInput() does not work on Windows.
        socket.configureBlocking(false);
        outstr = new SocketOutputStream(socket);
        instr = new SocketInputStream(socket);
    } catch (IOException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
    InetSocketAddress localSocketAddress = (InetSocketAddress) socket.socket().getLocalSocketAddress();
    localAddress = new SocketInetAddress(localSocketAddress.getAddress(), localSocketAddress.getPort());
    InetSocketAddress remoteSocketAddress = (InetSocketAddress) socket.socket().getRemoteSocketAddress();
    remoteAddress = new SocketInetAddress(remoteSocketAddress.getAddress(), remoteSocketAddress.getPort());
    objectReader = messageSerializer.newReader(streamSerializer.newDecoder(instr));
    encoder = streamSerializer.newEncoder(outstr);
    objectWriter = messageSerializer.newWriter(encoder);
}
 
開發者ID:lxxlxx888,項目名稱:Reer,代碼行數:20,代碼來源:SocketConnection.java

示例2: openSocketChannel

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public synchronized SocketChannel openSocketChannel(Address address) throws IOException {

        if (this.clientSocketChannel != null && this.clientSocketChannel.isOpen()) {
            return this.clientSocketChannel;
        }

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

        this.registerPendingMap.put(socketChannel, OP_CONNECT | OP_READ);
        this.selector.wakeup();

        LOG.info("Connecting to " + address + "...");
        socketChannel.connect(new InetSocketAddress(address.getHost(), address.getPort()));

        while (!socketChannel.finishConnect()) {

        }
        LOG.info("Connected.");

        this.clientSocketChannel = socketChannel;
        return this.clientSocketChannel;
    }
 
開發者ID:yiding-he,項目名稱:java-nio-test,代碼行數:24,代碼來源:SocketChannelClientHandler.java

示例3: connect

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public static SocketChannel connect(SocketAddress remote, final int timeoutMillis) {
    SocketChannel sc = null;
    try {
        sc = SocketChannel.open();
        sc.configureBlocking(true);
        sc.socket().setSoLinger(false, -1);
        sc.socket().setTcpNoDelay(true);
        sc.socket().setReceiveBufferSize(1024 * 64);
        sc.socket().setSendBufferSize(1024 * 64);
        sc.socket().connect(remote, timeoutMillis);
        sc.configureBlocking(false);
        return sc;
    } catch (Exception e) {
        if (sc != null) {
            try {
                sc.close();
            } catch (IOException e1) {
                logger.error(e1.getMessage(), e1);
            }
        }
    }

    return null;
}
 
開發者ID:lemonJun,項目名稱:TakinRPC,代碼行數:25,代碼來源:SelectorUtil.java

示例4: run

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void run() throws Exception
{
	NioThread nt=new NioThread();
	nt.start();
	Thread.sleep(1000);
	SocketChannel sc=SocketChannel.open();
	sc.configureBlocking(false);
	sc.connect(new InetSocketAddress("localhost", 9999));
	ChannelProcessorMultiplexer m=new ChannelProcessorMultiplexer(nt, sc, true,
			VideoServerTCPListener.clientID.getBytes(StandardCharsets.UTF_8),
			VideoServerTCPListener.serverID.getBytes(StandardCharsets.UTF_8));
	DuplexNioConnection conn=new DuplexNioConnection(m);
	m.start();
	CoolRMIClient client=new CoolRMIClient(getClass().getClassLoader(), new RMINioClientConnectionFactory(conn), false);
	Iremote r= (Iremote)client.getService(Iremote.class, Iremote.class.getName());
	System.out.println(""+r.getValue("Kitten"));
	System.out.println(""+r.getValue("Kitten"));
	System.out.println(""+r.getValue("Kitten"));
	System.out.println(""+r.getValue("Kitten"));
}
 
開發者ID:rizsi,項目名稱:rcom,代碼行數:21,代碼來源:RMINioClient.java

示例5: newHandle

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
/**
 * {@inheritDoc}
 */
@Override
protected SocketChannel newHandle(SocketAddress localAddress) throws Exception {
    SocketChannel ch = SocketChannel.open();

    int receiveBufferSize = (getSessionConfig()).getReceiveBufferSize();
    if (receiveBufferSize > 65535) {
        ch.socket().setReceiveBufferSize(receiveBufferSize);
    }

    if (localAddress != null) {
        ch.socket().bind(localAddress);
    }
    ch.configureBlocking(false);
    return ch;
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:19,代碼來源:NioSocketConnector.java

示例6: run

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public void run() {
	try {
		SelectionKey key;
		log.debug("運行連接請求處理與服務請求接收線程,線程ID:" + Thread.currentThread().getId());
		while (true) {
			selector.select();
			// 首先處理連接請求,並注冊連接後的Channel注冊到選擇器
			// 這種處理連接的方式,可能造成某一個選擇器注冊的Channel或選擇鍵比其他線程多,導致線程內的繁忙程度不一致
			while ((key = connQueue.poll()) != null) {
				ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
				// 接受一個連接
				SocketChannel sc = ssc.accept();
				sc.configureBlocking(false);
				sc.register(selector, SelectionKey.OP_READ);
				if (log.isDebugEnabled()) {
					log.debug("接受一個客戶端連接,處理連接請求的線程ID:" + Thread.currentThread().getId());
				}
			}

			// 再處理服務請求的選擇鍵,並將選擇鍵放入待處理服務隊列中
			Set<SelectionKey> keys = selector.selectedKeys();
			Iterator<SelectionKey> it = keys.iterator();
			while (it.hasNext()) {
				SelectionKey keytmp = it.next();
				it.remove();
				if (keytmp.isReadable()) {
					reqQueue.add(keytmp);
				}
			}
		}
	} catch (IOException e) {
		log.error("處理連接請求,並接收服務請求處理異常", e);
	}
}
 
開發者ID:minilynn,項目名稱:samplecode,代碼行數:35,代碼來源:Server.java

示例7: run

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void run() throws Exception
{
	NioThread nt=new NioThread();
	nt.start();
	Thread.sleep(1000);
	SocketChannel sc=SocketChannel.open();
	sc.configureBlocking(false);
	sc.connect(new InetSocketAddress("localhost", 9999));
	ChannelProcessorMultiplexer m=new ChannelProcessorMultiplexer(nt, sc, true,
			VideoServerTCPListener.clientID.getBytes(StandardCharsets.UTF_8),
			VideoServerTCPListener.serverID.getBytes(StandardCharsets.UTF_8));
	m.start();
	MainChannel mc=new MainChannel();
	mc.register(m);
}
 
開發者ID:rizsi,項目名稱:rcom,代碼行數:16,代碼來源:ExampleNioClient.java

示例8: initClient

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public void initClient(String ip, int port) throws IOException { // 獲得一個Socket通道
    SocketChannel channel = SocketChannel.open(); // 設置通道為非阻塞
    channel.configureBlocking(false); // 獲得一個通道管理器
    this.selector = Selector.open(); // 客戶端連接服務器,其實方法執行並沒有實現連接,需要在listen()方法中調
    channel.connect(new InetSocketAddress(ip, port));
    channel.register(selector, SelectionKey.OP_CONNECT);
}
 
開發者ID:laidu,項目名稱:java-learn,代碼行數:8,代碼來源:NioClient.java

示例9: run

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public void run() {
    try {
        SocketChannel sc = ssc.accept();
        sc.configureBlocking(true);
        execThPool.execute(new FDTNetPerfClient(sc));
    } catch (Throwable t) {
        t.printStackTrace();
    }
}
 
開發者ID:fast-data-transfer,項目名稱:fdt,代碼行數:10,代碼來源:FDTNetPerf.java

示例10: xferTest07

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
@Test
public void xferTest07() throws Exception { // for bug 5103988
    File source = File.createTempFile("source", null);
    source.deleteOnExit();

    FileChannel sourceChannel = new RandomAccessFile(source, "rw")
        .getChannel();
    sourceChannel.position(32000L)
        .write(ByteBuffer.wrap("The End".getBytes()));

    // The sink is a non-blocking socket channel
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(new InetSocketAddress(0));
    InetSocketAddress sa = new InetSocketAddress(
        InetAddress.getLocalHost(), ssc.socket().getLocalPort());
    SocketChannel sink = SocketChannel.open(sa);
    sink.configureBlocking(false);
    SocketChannel other = ssc.accept();

    long size = sourceChannel.size();

    // keep sending until congested
    long n;
    do {
        n = sourceChannel.transferTo(0, size, sink);
    } while (n > 0);

    sourceChannel.close();
    sink.close();
    other.close();
    ssc.close();
    source.delete();
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:34,代碼來源:Transfer.java

示例11: connect

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
public void connect(NioThread nt, SocketAddress address, byte[] thisId, byte[] otherId) throws Exception
{
	SocketChannel sc=SocketChannel.open();
	sc.configureBlocking(false);
	sc.connect(address);
	connect(nt, sc, true, thisId, otherId);
}
 
開發者ID:rizsi,項目名稱:rcom,代碼行數:8,代碼來源:CoolRMINioClient.java

示例12: createSock

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
/**
 * create a socket channel.
 * @return the created socket channel
 * @throws IOException
 */
SocketChannel createSock() throws IOException {
    SocketChannel sock;
    sock = SocketChannel.open();
    sock.configureBlocking(false);
    sock.socket().setSoLinger(false, -1);
    sock.socket().setTcpNoDelay(true);
    return sock;
}
 
開發者ID:maoling,項目名稱:fuck_zookeeper,代碼行數:14,代碼來源:ClientCnxnSocketNIO.java

示例13: openSocketChannelNonBlocking

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
/**
 * open non-blocking socket channel
 * @param msg
 * message
 * @return
 * SocketChannel
 */
public SocketChannel openSocketChannelNonBlocking(String msg) {
	SocketChannel socketChannel;
	do {
		try {
			socketChannel = SocketChannel.open();
			socketChannel.configureBlocking(false);
			return socketChannel;
		} catch (IOException e) {
			this.logger.warning(msg + e.toString());
		}
	} while (true);
}
 
開發者ID:luohaha,項目名稱:LightComm4J,代碼行數:20,代碼來源:Worker.java

示例14: 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

示例15: handleClients

import java.nio.channels.SocketChannel; //導入方法依賴的package包/類
private void handleClients() throws Exception {
    int selectCount = 0;
    while (true) {
        int createdCount = 0;
        synchronized (this) {
            if (connectionsNeeded > 0) {

                while (connectionsNeeded > 0 && createdCount < 20) {
                    connectionsNeeded--;
                    createdCount++;
                    totalCreated++;

                    SocketChannel channel = SocketChannel.open();
                    channel.configureBlocking(false);
                    channel.connect(address);
                    if (!channel.finishConnect()) {
                        channel.register(selector,
                                         SelectionKey.OP_CONNECT);
                    }
                }

                log("Started total of " +
                    totalCreated + " client connections");
                Thread.sleep(200);
            }
        }

        if (createdCount > 0) {
            selector.selectNow();
        } else {
            selectCount++;
            long startTime = System.nanoTime();
            selector.select();
            long duration = durationMillis(startTime);
            log("Exited clientSelector.select(), loop #"
                + selectCount + ", duration = " + duration + "ms");
        }

        int keyCount = -1;
        Iterator<SelectionKey> keys =
            selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = keys.next();
            synchronized (key) {
                keyCount++;
                keys.remove();
                if (!key.isValid()) {
                    log("Ignoring client key #" + keyCount);
                    continue;
                }
                int readyOps = key.readyOps();
                if (readyOps == SelectionKey.OP_CONNECT) {
                    key.interestOps(0);
                    ((SocketChannel) key.channel()).finishConnect();
                } else {
                    log("readyOps() on client key #" + keyCount +
                        " returned " + readyOps);
                }
            }
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:63,代碼來源:LotsOfCancels.java


注:本文中的java.nio.channels.SocketChannel.configureBlocking方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。