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


Java ServerSocketChannel.configureBlocking方法代碼示例

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


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

示例1: TunnelServer

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
public TunnelServer(int port, Selector selector) throws IOException {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    // ServerSocketChannel.bind() requires API 24
    serverSocketChannel.socket().bind(new InetSocketAddress(Inet4Address.getLoopbackAddress(), port));

    SelectionHandler socketChannelHandler = (selectionKey) -> {
        try {
            ServerSocketChannel channel = (ServerSocketChannel) selectionKey.channel();
            acceptClient(selector, channel);
        } catch (IOException e) {
            Log.e(TAG, "Cannot accept client", e);
        }
    };
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT, socketChannelHandler);
}
 
開發者ID:Genymobile,項目名稱:gnirehtet,代碼行數:17,代碼來源:TunnelServer.java

示例2: openServerSocket

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
public final void openServerSocket(InetAddress address, int tcpPort) throws IOException
{
	final ServerSocketChannel selectable = ServerSocketChannel.open();
	selectable.configureBlocking(false);
	
	final ServerSocket ss = selectable.socket();
	
	if (address != null)
	{
		ss.bind(new InetSocketAddress(address, tcpPort));
	}
	else
	{
		ss.bind(new InetSocketAddress(tcpPort));
	}
	
	selectable.register(_selector, SelectionKey.OP_ACCEPT);
}
 
開發者ID:rubenswagner,項目名稱:L2J-Global,代碼行數:19,代碼來源:SelectorThread.java

示例3: main

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
//            創建ServerSocketChannel,監聽8080端口
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(8080));
//            設置為非阻塞模式
        ssc.configureBlocking(false);
//            為ssc注冊選擇器
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
//            創建處理器
        Handler handler = new Handler(1024);
        while (true) {
//            等待請求,每次等待阻塞3s,超過3s後線程繼續向下運行,如果傳入0或者不傳參數將一直阻塞
            if (selector.select(3000) == 0) {
                System.out.println("等待請求超時……");
                continue;
            }
            System.out.println("處理請求……");
//            獲取待處理的SelectionKey
            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();
                try {
                    // 接收到連接請求時
                    if (key.isAcceptable()) {
                        handler.handleAccept(key);
                    }
//            讀數據
                    if (key.isReadable()) {
                        handler.handleRead(key);
                    }
                } catch (IOException ex) {
                    keyIter.remove();
                    continue;
                }
//            處理完後,從待處理的SelectionKey迭代器中移除當前所使用的key
                keyIter.remove();
            }
        }
    }
 
開發者ID:tomoncle,項目名稱:JavaStudy,代碼行數:41,代碼來源:NIOSocketTest.java

示例4: main

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
//    創建ServerSocketChannel,監聽8080端口
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.socket().bind(new InetSocketAddress(8080));
//    設置為非阻塞模式
        ssc.configureBlocking(false);
//    為ssc注冊選擇器
        Selector selector = Selector.open();
        ssc.register(selector, SelectionKey.OP_ACCEPT);
//    創建處理器
        while (true) {
//    等待請求,每次等待阻塞3s,超過3s後線程繼續向下運行,
//    如果傳入0或者不傳參數將一直阻塞
            if (selector.select(3000) == 0) {
                continue;
            }
//    獲取待處理的SelectionKey
            Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
            while (keyIter.hasNext()) {
                SelectionKey key = keyIter.next();
//    啟動新線程處理SelectionKey
                new Thread(new HttpHandler(key)).run();
//    處理完後,從待處理的SelectionKey迭代器中移除當前所使用的key
                keyIter.remove();
            }
        }
    }
 
開發者ID:tomoncle,項目名稱:JavaStudy,代碼行數:28,代碼來源:HttpTest.java

示例5: run

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
private void run() throws Exception
{
	NioThread nt=new NioThread();
	nt.start();
	Thread.sleep(1000);
	ServerSocketChannel ssc=ServerSocketChannel.open();
	ssc.configureBlocking(false);
	ssc.bind(new InetSocketAddress("localhost", 9999));
	SocketAcceptor sa=new SocketAcceptor(nt, ssc);
	sa.start();
}
 
開發者ID:rizsi,項目名稱:rcom,代碼行數:12,代碼來源:ExampleNioServer.java

示例6: newSocket

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
private static ServerSocketChannel newSocket() {
    try {
        ServerSocketChannel ch = ServerSocketChannel.open();
        ch.configureBlocking(false);
        return ch;
    } catch (IOException e) {
        throw new NioException("Open a server socket error:" + e.getMessage(), e);
    }
}
 
開發者ID:lemonJun,項目名稱:TakinRPC,代碼行數:10,代碼來源:NioServerProcessor.java

示例7: start

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
private void start() throws Exception {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(port));
    serverSocketChannel.configureBlocking(false);

    selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
        selector.select(); // 此處的select方法是阻塞的
        // 對所有的key做一次遍曆,由key本身判斷此事件是否與自己有關
        selector.selectedKeys().forEach((this::handleKey));
    }
}
 
開發者ID:RitterHou,項目名稱:Geisha,代碼行數:14,代碼來源:NioServer.java

示例8: open

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
/**
 * {@inheritDoc}
 */
@Override
protected ServerSocketChannel open(SocketAddress localAddress) throws Exception {
    // Creates the listening ServerSocket
    ServerSocketChannel channel = ServerSocketChannel.open();

    boolean success = false;

    try {
        // This is a non blocking socket channel
        channel.configureBlocking(false);

        // Configure the server socket,
        ServerSocket socket = channel.socket();

        // Set the reuseAddress flag accordingly with the setting
        socket.setReuseAddress(isReuseAddress());

        // and bind.
        socket.bind(localAddress, getBacklog());

        // Register the channel within the selector for ACCEPT event
        channel.register(selector, SelectionKey.OP_ACCEPT);
        success = true;
    } finally {
        if (!success) {
            close(channel);
        }
    }
    return channel;
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:34,代碼來源:NioSocketAcceptor.java

示例9: waitForTask

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
private void waitForTask() throws Exception {
    if (!DirectByteBufferPool.initInstance(config.getByteBufferSize(), Config.getMaxTakePollIter())) {
        // this is really wrong ... It cannot be already initialized
        throw new FDTProcolException("The buffer pool cannot be already initialized");
    }

    ExecutorService executor = null;
    ServerSocketChannel ssc = null;
    ServerSocket ss = null;
    Selector sel = null;
    try {
        executor = Utils.getStandardExecService("[ Acceptable ServersThreadPool ] ",
                2,
                10,
                new ArrayBlockingQueue<Runnable>(65500),
                Thread.NORM_PRIORITY - 2);
        ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        ss = ssc.socket();
        ss.bind(new InetSocketAddress(config.getPort()));
        sel = Selector.open();
        ssc.register(sel, SelectionKey.OP_ACCEPT);
        System.out.println("READY");
        Utils.waitAndWork(executor, ss, sel, config);
    } finally {
        logger.log(Level.INFO, "[FDT] [ waitForTask ] main loop FINISHED!");
        // close all the stuff
        Utils.closeIgnoringExceptions(ssc);
        Utils.closeIgnoringExceptions(sel);
        Utils.closeIgnoringExceptions(ss);
        if (executor != null) {
            executor.shutdown();
        }
    }
}
 
開發者ID:fast-data-transfer,項目名稱:fdt,代碼行數:36,代碼來源:FDT.java

示例10: bindToPort

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
@VisibleForTesting
ServerSocketChannel bindToPort() throws IOException {
    // Bind to the first available port in the range
    ServerSocketChannel channel = null;

    for (int port = ConnectionHandler.PORT_RANGE_START; port <= ConnectionHandler.PORT_RANGE_END; port++) {
        final InetSocketAddress tryAddress = new InetSocketAddress(InetAddress.getLocalHost(), port);


        try {
            channel = ServerSocketChannel.open();
            channel.socket().bind(tryAddress);
            channel.configureBlocking(false);
            break;
        } catch (final IOException ioe) {
            // Ignore, try next port
            logger.warn("Could not bind to {}, trying next port...", tryAddress);
            try {
                if (channel != null) channel.close();
            } catch (final IOException ignored) {
            }
        }
    }

    if (channel == null || !channel.socket().isBound()) {
        throw new IOException("No available port for the BitTorrent client!");
    }
    return channel;
}
 
開發者ID:anthonyraymond,項目名稱:joal,代碼行數:30,代碼來源:ConnectionHandler.java

示例11: openServerSocketChannelNonBlocking

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

示例12: run

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
private void run() throws Exception
{
	NioThread nt=new NioThread();
	nt.start();
	Thread.sleep(1000);
	ServerSocketChannel ssc=ServerSocketChannel.open();
	ssc.configureBlocking(false);
	ssc.bind(new InetSocketAddress("localhost", 9999));
	RMINioConnectionServer niosrv=new RMINioConnectionServer();
	RMISocketAcceptor sa=new RMISocketAcceptor(nt, ssc, niosrv);
	sa.start();
	CoolRMIServer srv=new CoolRMIServer(getClass().getClassLoader(), new RMINioConnectionServerFactory(niosrv), false);
	srv.getServiceRegistry().addService(new CoolRMIService(Iremote.class.getName(), Iremote.class, new Remote()));
	srv.start();
}
 
開發者ID:rizsi,項目名稱:rcom,代碼行數:16,代碼來源:RMINioServer.java

示例13: listen

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
public SA listen(NioThread nt, SocketAddress address, byte[] thisId, byte[] otherId) throws Exception
{
	ServerSocketChannel ssc=ServerSocketChannel.open();
	ssc.configureBlocking(false);
	ssc.bind(address);
	SA sa=new SA(nt, ssc, thisId, otherId);
	sa.start();
	return sa;
}
 
開發者ID:rizsi,項目名稱:rcom,代碼行數:10,代碼來源:CoolRMINioServer.java

示例14: openForProject

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
/**
 * Registers the connection and initiates the listening socket.
 * @param project the project which is being run / debugged
 * @param debugger if true, the connection will pair with a debugger session.
 */
public ShellAgent openForProject(Project p, boolean debugger) throws IOException {
    ServerSocket ss;
    
    String encodedKey;
    boolean shouldInit = false;
    
    synchronized (this) {
        shouldInit = usedKeys.isEmpty();
        do {
            BigInteger key = BigInteger.probablePrime(64, keyGenerator);
            encodedKey = key.toString(Character.MAX_RADIX);
        } while (!usedKeys.add(encodedKey));
    }
    
    if (shouldInit) {
        init();
    }
    
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);
    SocketAddress local = new InetSocketAddress(
        // PENDING: choose something better for remote debugging!
        InetAddress.getLoopbackAddress(),
        0);
    ssc.bind(local);
    ssc.accept();
    ss = ssc.socket();
    LOG.log(Level.FINE, "Creating new server socket {0} for project: {1}", new Object[] {
        ss, p
    });
    ShellAgent agent = new ShellAgent(this, p, ss, encodedKey, debugger);
    synchronized (this) {
        registeredAgents.put(encodedKey, agent);
    }
    synchronized (requests) {
        servers.wakeup();
        requests.add(agent);
        
    }
    return agent;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:47,代碼來源:ShellLaunchManager.java

示例15: startServer

import java.nio.channels.ServerSocketChannel; //導入方法依賴的package包/類
private void startServer() throws Exception{
        //聲明一個selector
        selector= SelectorProvider.provider().openSelector();

        //聲明一個server socket channel,而且是非阻塞的。
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);

//        InetSocketAddress isa=new InetSocketAddress(InetAddress.getLocalHost(),8000);
        //聲明服務器端的端口
        InetSocketAddress isa=new InetSocketAddress(8000);
        //服務器端的socket channel綁定在這個端口。
        ssc.socket().bind(isa);
        //把一個socketchannel注冊到一個selector上,同時選擇監聽的事件,SelectionKey.OP_ACCEPT表示對selector如果
        //監聽到注冊在它上麵的server socket channel準備去接受一個連接,或 有個錯誤掛起,selector將把OP_ACCEPT加到
        //key ready set 並把key加到selected-key set.
        SelectionKey acceptKey=ssc.register(selector,SelectionKey.OP_ACCEPT);

        for(;;){
            selector.select();
            Set readyKeys=selector.selectedKeys();
            Iterator i=readyKeys.iterator();
            long e=0;
            while (i.hasNext()){
                SelectionKey sk=(SelectionKey)i.next();
                i.remove();

                if(sk.isAcceptable()){
                    doAccept(sk);
                }else if(sk.isValid()&&sk.isReadable()){
                    if(!geym_time_stat.containsKey(((SocketChannel)sk.channel()).socket())){
                        geym_time_stat.put(((SocketChannel)sk.channel()).socket(),System.currentTimeMillis());
                        doRead(sk);
                    }
                }else if(sk.isValid()&&sk.isWritable()){
                    doWrite(sk);
                    e=System.currentTimeMillis();
                    long b=geym_time_stat.remove(((SocketChannel)sk.channel()).socket());
                    System.out.println("spend"+(e-b)+"ms");
                }
            }
        }
    }
 
開發者ID:sean417,項目名稱:LearningOfThinkInJava,代碼行數:44,代碼來源:MultiThreadNIOEchoServer.java


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