当前位置: 首页>>代码示例>>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;未经允许,请勿转载。