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


Java AsynchronousSocketChannel类代码示例

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


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

示例1: AioServerConnection

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
public AioServerConnection(AsynchronousSocketChannel channel) {
    this.channel = channel;
    this.reader = new MsgReader(channel) {
        @Override
        protected void onMsg(Msg msg) {
            Command command = MsgConverter.convert(msg);
            Reply reply = commandHandler.handle(command);
            writer.write(reply.toMsg());
        }
    };
    this.writer = new MsgWriter(channel) {
        @Override
        protected void onWriteDone() {
            super.onWriteDone();
            processCommand();
        }
    };
}
 
开发者ID:altiplanogao,项目名称:io-comparison,代码行数:19,代码来源:AioServerConnection.java

示例2: completed

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
/**
 *@description 接收客户端请求成功之后回调
 *@time 创建时间:2017年7月20日上午11:05:16
 *@param channel
 *@param serverHandler
 *@author dzn
 */
@Override
public void completed(AsynchronousSocketChannel channel,
        AsyncTimeServerHandler serverHandler) {
    
    System.out.println("成功接收到客户端连接 : " + channel.toString());
    
    //继续注册一个接收请求的处理类
    serverHandler.asynchronousServerSocketChannel.accept(serverHandler, this);
    
    //创建一个数据缓冲区
    ByteBuffer bb = ByteBuffer.allocate(1024);
    
    //去读取客户端发送的数据,并注册一个数据处理类
    channel.read(bb, bb, new ReadCompletionHandler(channel));
}
 
开发者ID:SnailFastGo,项目名称:netty_op,代码行数:23,代码来源:AcceptCompletionHandler.java

示例3: make

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
@SuppressWarnings({"unchecked", "rawtypes"})
public MySQLConnection make(MySQLDataSource pool, ResponseHandler handler,
                            String schema) throws IOException {

    DBHostConfig dsc = pool.getConfig();
    NetworkChannel channel = openSocketChannel(DbleServer.getInstance().isAIO());

    MySQLConnection c = new MySQLConnection(channel, pool.isReadNode());
    c.setSocketParams(false);
    c.setHost(dsc.getIp());
    c.setPort(dsc.getPort());
    c.setUser(dsc.getUser());
    c.setPassword(dsc.getPassword());
    c.setSchema(schema);
    c.setHandler(new MySQLConnectionAuthenticator(c, handler));
    c.setPool(pool);
    c.setIdleTimeout(pool.getConfig().getIdleTimeout());
    if (channel instanceof AsynchronousSocketChannel) {
        ((AsynchronousSocketChannel) channel).connect(
                new InetSocketAddress(dsc.getIp(), dsc.getPort()), c,
                (CompletionHandler) DbleServer.getInstance().getConnector());
    } else {
        ((NIOConnector) DbleServer.getInstance().getConnector()).postConnect(c);
    }
    return c;
}
 
开发者ID:actiontech,项目名称:dble,代码行数:27,代码来源:MySQLConnectionFactory.java

示例4: handleNewConnection

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
/**
   * Creates a new client and adds it to the list of connections.
   * Sets the clients handler to the initial state of NameReader
   *
   * @param channel the newly accepted channel
   */
private void handleNewConnection(AsynchronousSocketChannel channel) {
	try {
		channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
	} catch (IOException e) {
		// ignore
		//
		e.printStackTrace();
	}

	//new dealer and channel
	AioServerDataDealer dealer = null;
	
	dealer = aioDataDealerFactory.getAioServerDataDealer();
	
	int channelId = getChannelId();
	AioServerChannel aioChannel = new AioServerChannel(channelId, channel, dealer, this);
	connections.put(channelId, aioChannel);
	
	//start channel
	aioChannel.run(null);
}
 
开发者ID:psfu,项目名称:waterwave,代码行数:28,代码来源:AioServer.java

示例5: setAsynchronousSocketChannel

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
/**
 * @param asynchronousSocketChannel the asynchronousSocketChannel to set
 */
public void setAsynchronousSocketChannel(AsynchronousSocketChannel asynchronousSocketChannel)
{
	this.asynchronousSocketChannel = asynchronousSocketChannel;

	if (asynchronousSocketChannel != null)
	{
		try
		{
			Node clientNode = createClientNode(asynchronousSocketChannel);
			setClientNode(clientNode);
		} catch (IOException e)
		{
			log.info(e.toString(), e);
			assignAnUnknownClientNode();
		}
	} else
	{
		assignAnUnknownClientNode();
	}
}
 
开发者ID:tywo45,项目名称:talent-aio,代码行数:24,代码来源:ChannelContext.java

示例6: retry

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
private void retry() {
    try {
        TimeUnit.SECONDS.sleep(1);
        if (null != this.channel && this.channel.isOpen()) {
            this.channel.close();
        }
        log.debug("连接:{}", this.socketAddress.toString());
        final AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open(this.group);
        asynchronousSocketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
        asynchronousSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
        asynchronousSocketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
        asynchronousSocketChannel.connect(this.socketAddress).get(5, TimeUnit.SECONDS);
        this.channel = new FastChannel(asynchronousSocketChannel, this.serializer, timeout);
    } catch (final Exception e) {
        retry();
    }
}
 
开发者ID:sd4324530,项目名称:fastrpc,代码行数:18,代码来源:FastRpcClient.java

示例7: acceptCompletionHandler

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
private CompletionHandler<AsynchronousSocketChannel, Integer> acceptCompletionHandler(
			int byteCount, AsynchronousServerSocketChannel socket) {
		return new CompletionHandler<AsynchronousSocketChannel, Integer>() {
			public void completed(
					AsynchronousSocketChannel ch,
					Integer acceptsToGo) {
				acceptsToGo = acceptsToGo-1;
//				System.out.println("server accepted, to go = " + acceptsToGo);
				writeStuffThreadAsync(socket, ch, byteCount, acceptsToGo);
				if (acceptsToGo > 0) {
					socket.accept(acceptsToGo, acceptCompletionHandler(byteCount, socket));
				}
			}
			public void failed(Throwable exc, Integer attachment) {
				exc.printStackTrace();
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
	}
 
开发者ID:arienkock,项目名称:parallelism-benchmarks,代码行数:24,代码来源:FountainSocketBenchmark.java

示例8: completed

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
@Override
public void completed(AsynchronousSocketChannel socketChannel, AioServerSocket serverSocket) {
	try {
		//接续接收 accept 请求
		serverSocket.catchAccept();
		
		AioSocket socket = new AioSocket(serverSocket,socketChannel);
		
		//触发 Accept 事件
		EventTrigger.fireAcceptThread(socket.getSession());
		
		
	} catch (IOException e) {
		EventTrigger.fireExceptionThread(null, e);
	}
}
 
开发者ID:helyho,项目名称:Voovan,代码行数:17,代码来源:AcceptCompletionHandler.java

示例9: main

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
public static void main(String[] args) throws IOException, ExecutionException,
          InterruptedException, TimeoutException {
    //打开 AsychronousServerSocketChannel 并将其绑定到类似于 ServerSocketChannel 的地址
    //方法 bind() 将一个套接字地址作为其参数。找到空闲端口的便利方法是传递一个 null 地址,它会自动将套接字绑定到本地主机地址,并使用空闲的 临时 端口。
    AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open().bind(null);
    //告诉通道接受一个连接
    Future<AsynchronousSocketChannel> future = server.accept();

//    利用 Future 对象,当前线程可阻塞来等待结果:
    AsynchronousSocketChannel worker = future.get();
    //超时
    //AsynchronousSocketChannel worker = future.get(10, TimeUnit.SECONDS);
    //取消
//    if (!future.isDone()) {
//      future.cancel(true);//cancel() 方法可利用一个布尔标志来指出执行接受的线程是否可被中断
//    }
//
//// read a message from the client
    ByteBuffer readBuffer = ByteBuffer.allocate(1024);
    worker.read(readBuffer).get(10, TimeUnit.SECONDS);
    System.out.println("Message: " + new String(readBuffer.array()));
  }
 
开发者ID:edgar615,项目名称:javase-study,代码行数:23,代码来源:AsynchronousServerSocketMain.java

示例10: Nio2SSLSocket

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
public Nio2SSLSocket(AsynchronousSocketChannel sock, SSLContext sslc, boolean clientMode)
{
	super(sock);
	this.engine = sslc.createSSLEngine();
	this.engine.setUseClientMode(clientMode);
	String[] procols = { "TLSv1" };
	this.engine.setEnabledProtocols(procols);

	int packetBufferSize = engine.getSession().getPacketBufferSize();
	decodeBuf	= ByteBuffer.allocateDirect(packetBufferSize);
	readBuf = ByteBuffer.allocateDirect(packetBufferSize);
	
	for (int i = 0; i < 2; i++)
	{
		writeBufs[i] = ByteBuffer.allocateDirect(packetBufferSize);
		writeBufs[i].limit(0);
	}
	writeBufs[0].clear();
}
 
开发者ID:EricssonResearch,项目名称:trap,代码行数:20,代码来源:Nio2SSLSocket.java

示例11: connect

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
private void connect() throws BindException{
	String errorMessage = "";
	if (socketChannel == null || !socketChannel.isOpen() || closed) {
		try {
			socketChannel = AsynchronousSocketChannel.open();
			socketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
			socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
			socketChannel.connect(new InetSocketAddress(ip, port)).get(timeout, TimeUnit.MILLISECONDS);
			closed = false;
			
			//when connect to the server, keep receiving data either server response or server call
			receive();
		} catch (Exception e) {
			log.error("Connection error: " + e.getMessage());
			errorMessage = e.getMessage();
		}
	}
	if (socketChannel == null) {
		throw new BindException(errorMessage);
	}
}
 
开发者ID:zijan,项目名称:Tatala-RPC,代码行数:22,代码来源:LongClientSession.java

示例12: connect

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
private void connect() throws BindException{
	String errorMessage = "";
	if (socketChannel == null || !socketChannel.isOpen() || closed) {
		try {
			socketChannel = AsynchronousSocketChannel.open();
			socketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
			socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);
			socketChannel.connect(new InetSocketAddress(ip, port)).get(timeout, TimeUnit.MILLISECONDS);
			closed = false;
			log.debug("Session start to " + socketChannel.getRemoteAddress());
			
			//when connect to the server, keep receiving data either server response or server call
			receive();
		} catch (Exception e) {
			log.error("Connection error: " + e.getMessage());
			errorMessage = e.getMessage();
		}
	}
	if (socketChannel == null) {
		throw new BindException(errorMessage);
	}
}
 
开发者ID:zijan,项目名称:Tatala-RPC,代码行数:23,代码来源:LongClientSession.java

示例13: make

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
public MySQLConnection make(MySQLDataSource pool, ResponseHandler handler)
		throws IOException {

	DBHostConfig dsc = pool.getConfig();
	AsynchronousSocketChannel channel = openSocketChannel();
	MySQLConnection c = new MySQLConnection(channel, pool.isReadNode());

	c.setHost(dsc.getIp());
	c.setPort(dsc.getPort());
	c.setUser(dsc.getUser());
	c.setPassword(dsc.getPassword());
	// c.setSchema(dsc.getDatabase());
	c.setHandler(new MySQLConnectionAuthenticator(c, handler));
	c.setPool(pool);
	c.setIdleTimeout(pool.getConfig().getIdleTimeout());
	channel.connect(new InetSocketAddress(dsc.getIp(), dsc.getPort()), c,
			MycatServer.getInstance().getConnector());
	return c;
}
 
开发者ID:youngor,项目名称:openclouddb,代码行数:20,代码来源:MySQLConnectionFactory.java

示例14: SocketSession

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
public SocketSession(AsynchronousSocketChannel channel, ByteBuffer buffer,
		CodecFactory codecFactory) throws IOException {
	this.channel = channel;
	this.remoteAddress = channel.getRemoteAddress();
	this.processor = new Processor(this);
	this.buffer = buffer;
	this.codec = codecFactory.getCodec();
	this.describe = "local:" + channel.getLocalAddress() + " remote:"
			+ remoteAddress + " hashCode/" + super.hashCode();
	this.hashCode = super.hashCode();
	attachment = new ConcurrentHashMap<Object, Object>(128);
	this.attachment.put(MSG_SURPLUS_LENGTH, -1);
	this.attachment.put(MSG_TMP, new byte[0]);
	this.remotePort = Integer.parseInt(this.toString().split(" ")[1]
			.split(":")[2]);
}
 
开发者ID:finikes,项目名称:tridge,代码行数:17,代码来源:SocketSession.java

示例15: AbstractClient

import java.nio.channels.AsynchronousSocketChannel; //导入依赖的package包/类
/**
 * Construct a new {@code Client}
 * @param channel that this client listens on
 * @throws IOException If an I/O error occurs
 */
AbstractClient(AsynchronousSocketChannel channel) {
	super();
	this.channel = channel;
	this.cipher = new Cryptographer();
	/*
	 * TODO This option was part of the ChatServer example by Oracle, but
	 * should be used with caution: "The socket option should only be
	 * enabled in cases where it is known that the coalescing impacts
	 * performance". We need to figure out whether it is required to set
	 * this option to true.
	 * 
	 * try {
	 * 	this.channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
	 * } catch (IOException e) {
	 *	e.printStackTrace();
	 * }
	 * 
	 */
}
 
开发者ID:jackpotsvr,项目名称:Java-Conquer-Server,代码行数:25,代码来源:AbstractClient.java


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