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


Java ServerSocketChannel.register方法代码示例

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


在下文中一共展示了ServerSocketChannel.register方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: openServerSocket

import java.nio.channels.ServerSocketChannel; //导入方法依赖的package包/类
public final void openServerSocket(InetAddress address, int tcpPort) throws IOException
{
    ServerSocketChannel selectable = ServerSocketChannel.open();
    selectable.configureBlocking(false);

    ServerSocket ss = selectable.socket();
    
    if (address == null)
        ss.bind(new InetSocketAddress(tcpPort));
    else
        ss.bind(new InetSocketAddress(address, tcpPort));
    
    selectable.register(_selector, SelectionKey.OP_ACCEPT);
}
 
开发者ID:L2jBrasil,项目名称:L2jBrasil,代码行数:15,代码来源:SelectorThread.java

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

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

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

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

示例10: startServer

import java.nio.channels.ServerSocketChannel; //导入方法依赖的package包/类
/**
 * 用于启动NIO Server
 */
private void startServer() throws Exception {
    //通过工厂方法获得一个Selector对象的实例
    selector = SelectorProvider.provider().openSelector();
    //获得表示服务端的SocketChannel实例
    ServerSocketChannel ssc = ServerSocketChannel.open();
    //将这个SocketChannel设置为非阻塞模式。实际上,Channel也可以像传统的Socket那样按照阻塞的方式工作
    //但在这里,更倾向于让其工作在非阻塞模式,在这种模式下,我们才可以向Channel注册感兴趣的事件,并且在数据准备好时,得到必要的通知
    ssc.configureBlocking(false);
    //将Channel绑定在8000端口。
    InetSocketAddress isa = new InetSocketAddress(/*InetAddress.getLocalHost()*/"localhost", 8000);
    ssc.socket().bind(isa);
    //将ServerSocketChannel绑定到Selector上,并注册它感兴趣的事件为Accept
    //当Selector发现ServerSocketChannel有新的客户端连接时,就会通知ServerSocketChannel进行处理。
    //方法register()的返回值是一个SelectionKey,SelectionKey表示一对Selector和Channel的关系。
    //当Channel注册到Selector上时,就相当于确立了两者的服务关系,那么SelectionKey就是这个契约。
    //当Selector或者Channel被关闭时,它们对应的SelectionKey就会失效。
    SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
    //无穷循环,它的主要任务就是等待-分发网络消息
    for (; ; ) {
        //select()方法是一个阻塞方法。如果当前没有任何数据准备好,它就会等待。一旦有数据可读,它就会返回。它的返回值是已经准备就绪的SelectionKey的数量。
        selector.select();
        //获取那些准备好的SelectionKey
        Set readyKeys = selector.selectedKeys();
        Iterator i = readyKeys.iterator();
        long e = 0;
        while (i.hasNext()) {
            SelectionKey sk = (SelectionKey) i.next();
            //将这个元素移除!注意,这个非常重要,否则就会重复处理相同的SelectionKey
            i.remove();
            //判断当前SelectionKey所代表的Channel是否在Acceptable状态,如果是,就进行客户端的接收(执行doAccept()方法)
            if (sk.isAcceptable()) {
                doAccept(sk);
                //判断Channel是否已经可以读了,如果是就进行读取(doRead()方法)
            } else if (sk.isValid() && sk.isReadable()) {
                if (!time_stat.containsKey(((SocketChannel) sk.channel()).socket()))
                    time_stat.put(((SocketChannel) sk.channel()).socket(), System.currentTimeMillis());
                doRead(sk);
                //判断通道是否准备好进行写。如果是就进行写入(doWrite()方法),同时在写入完成后,根据读取前的时间戳,输出处理这个Socket连接的耗时。
            } else if (sk.isValid() && sk.isWritable()) {

                doWrite(sk);
                e = System.currentTimeMillis();
                long b = time_stat.remove(((SocketChannel) sk.channel()).socket());
                System.out.println("spend:" + (e - b) + "ms");

            }
        }
    }
}
 
开发者ID:zhangboqing,项目名称:multithread,代码行数:53,代码来源:NIOEchoServer.java

示例11: start

import java.nio.channels.ServerSocketChannel; //导入方法依赖的package包/类
public void start() {
	ServerSocketChannel ssc = null;
	try {
		selector = Selector.open();
		ssc = ServerSocketChannel.open();
		ssc.socket().bind(new InetSocketAddress(port));
		ssc.configureBlocking(false);
		ssc.register(selector, SelectionKey.OP_ACCEPT);
		log.info("start success,listen on port " + port);

		while (true) {
			/**
			 * select操作执行时其他线程register,将会阻塞.可以在任意时刻关闭通道或者取消键.
			 * 因为select操作并未对Key.cancell()同步,因此有可能再selectedKey中出现的key是已经被取消的.
			 * 这一点需要注意.需要校验:key.isValid() && key.isReadable()
			 */
			if (selector.select(500) == 0) {
				continue;
			}
			Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
			while (iter.hasNext()) {
				SelectionKey key = iter.next();
				if (key.isAcceptable()) {
					log.info("server recieve an accept");
					handleAccept(key);
				}
				if (key.isValid() && key.isReadable()) {
					log.info("server recieve a read");
					handleRead(key);
				}
				if (key.isWritable() && key.isValid()) {
					log.info("server recieve a write");
					handleWrite(key);
				}
				if (key.isConnectable()) {
					log.info("server recieve a isConnectable = true");
				}
				if (!key.isValid()){
					key.cancel();
					log.error("");
				}
				iter.remove();
			}
		}

	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
开发者ID:spafka,项目名称:spark_deep,代码行数:50,代码来源:NioServer.java

示例12: runTest

import java.nio.channels.ServerSocketChannel; //导入方法依赖的package包/类
static void runTest(int initCount, int massCount, int maxSelectTime)
        throws Exception {
    testStartTime = System.nanoTime();

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359);

    // Create server channel, add it to selector and run epoll_ctl.
    log("Setting up server");
    Selector serverSelector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(address, 5000);
    server.register(serverSelector, SelectionKey.OP_ACCEPT);
    serverSelector.selectNow();

    log("Setting up client");
    ClientThread client = new ClientThread(address);
    client.start();
    Thread.sleep(100);

    // Set up initial set of client sockets.
    log("Starting initial client connections");
    client.connectClients(initCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all initial client sockets, add to selector and run
    // epoll_ctl.
    log("Accepting initial connections");
    List<SocketChannel> serverChannels1 =
        acceptAndAddAll(serverSelector, server, initCount);
    if (serverChannels1.size() != initCount) {
        throw new Exception("Accepted " + serverChannels1.size() +
                            " instead of " + initCount);
    }
    serverSelector.selectNow();

    // Set up mass set of client sockets.
    log("Requesting mass client connections");
    client.connectClients(massCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all mass client sockets, add to selector and do NOT
    // run epoll_ctl.
    log("Accepting mass connections");
    List<SocketChannel> serverChannels2 =
        acceptAndAddAll(serverSelector, server, massCount);
    if (serverChannels2.size() != massCount) {
        throw new Exception("Accepted " + serverChannels2.size() +
                            " instead of " + massCount);
    }

    // Close initial set of sockets.
    log("Closing initial connections");
    closeAll(serverChannels1);

    // Now get the timing of select() call.
    log("Running the final select call");
    long startTime = System.nanoTime();
    serverSelector.selectNow();
    long duration = durationMillis(startTime);
    log("Init count = " + initCount +
        ", mass count = " + massCount +
        ", duration = " + duration + "ms");

    if (duration > maxSelectTime) {
        System.out.println
            ("\n\n\n\n\nFAILURE: The final selectNow() took " +
             duration + "ms " +
             "- seems like O(N^2) bug is still here\n\n");
        System.exit(1);
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:73,代码来源:LotsOfCancels.java

示例13: initServer

import java.nio.channels.ServerSocketChannel; //导入方法依赖的package包/类
public void initServer(int port) throws Exception {

        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        serverChannel.socket().bind(new InetSocketAddress(port));

        this.selector = Selector.open();

        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

    }
 
开发者ID:laidu,项目名称:java-learn,代码行数:12,代码来源:NioServer.java


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