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


Java SocketChannel类代码示例

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


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

示例1: Client

import java.nio.channels.SocketChannel; //导入依赖的package包/类
public Client(Selector selector, SocketChannel clientChannel, CloseListener<Client> closeListener) throws ClosedChannelException {
    id = nextId++;
    this.clientChannel = clientChannel;
    router = new Router(this, selector);
    pendingIdBuffer = createIntBuffer(id);

    SelectionHandler selectionHandler = (selectionKey) -> {
        if (selectionKey.isValid() && selectionKey.isWritable()) {
            processSend();
        }
        if (selectionKey.isValid() && selectionKey.isReadable()) {
            processReceive();
        }
        if (selectionKey.isValid()) {
            updateInterests();
        }
    };
    // on start, we are interested only in writing (we must first send the client id)
    interests = SelectionKey.OP_WRITE;
    selectionKey = clientChannel.register(selector, interests, selectionHandler);

    this.closeListener = closeListener;
}
 
开发者ID:Genymobile,项目名称:gnirehtet,代码行数:24,代码来源:Client.java

示例2: createFrameBuffer

import java.nio.channels.SocketChannel; //导入依赖的package包/类
@Override
protected FrameBuffer createFrameBuffer(TNonblockingTransport trans, SelectionKey selectionKey,
                                        AbstractSelectThread selectThread) {
    TrackingFrameBuffer frameBuffer = new TrackingFrameBuffer(trans, selectionKey, selectThread);
    if (trans instanceof TNonblockingSocket) {
        try {
            SocketChannel socketChannel = ((TNonblockingSocket) trans).getSocketChannel();
            InetAddress addr = ((InetSocketAddress) socketChannel.getRemoteAddress()).getAddress();
            clientAddresses.put(frameBuffer.getInputFramedTransport(), addr);
        } catch (IOException e) {
            log.warn("Exception while tracking client address", e);
            clientAddresses.remove(frameBuffer.getInputFramedTransport());
        }
    } else {
        log.warn("Unknown TNonblockingTransport instance: {}", trans.getClass().getName());
        clientAddresses.remove(frameBuffer.getInputFramedTransport());
    }
    return frameBuffer;
}
 
开发者ID:shlee89,项目名称:athena,代码行数:20,代码来源:Bmv2ControlPlaneThriftServer.java

示例3: NioTcpMessageChannel

import java.nio.channels.SocketChannel; //导入依赖的package包/类
protected NioTcpMessageChannel(NioTcpMessageProcessor nioTcpMessageProcessor,
		SocketChannel socketChannel) throws IOException {
	super(nioTcpMessageProcessor.getSIPStack());
	super.myClientInputStream = socketChannel.socket().getInputStream();
	try {
		this.peerAddress = socketChannel.socket().getInetAddress();
		this.peerPort = socketChannel.socket().getPort();
		this.socketChannel = socketChannel;
		super.mySock = socketChannel.socket();
		// messages that we write out to him.
		nioParser = new NioPipelineParser(sipStack, this,
				this.sipStack.getMaxMessageSize());
		this.peerProtocol = nioTcpMessageProcessor.transport;
		lastActivityTimeStamp = System.currentTimeMillis();
		super.key = MessageChannel.getKey(peerAddress, peerPort, nioTcpMessageProcessor.transport);

           myAddress = nioTcpMessageProcessor.getIpAddress().getHostAddress();
           myPort = nioTcpMessageProcessor.getPort();

	} finally {
		if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
			logger.logDebug("Done creating NioTcpMessageChannel " + this + " socketChannel = " +socketChannel);
		}
	}

}
 
开发者ID:YunlongYang,项目名称:LightSIP,代码行数:27,代码来源:NioTcpMessageChannel.java

示例4: getData

import java.nio.channels.SocketChannel; //导入依赖的package包/类
private void getData(ByteBuffer input, SocketChannel channel) {
	int id = input.getInt();
	byte[] entity = data.get(id);

	ByteBuffer outputBuffer = TCPServer.prepareEmptyBuffer();
	int entityOffset = 0;

	while ((entity.length - entityOffset) > TCPServer.MAX_MESSAGE_BYTES) {
		outputBuffer.rewind();
		outputBuffer.put(entity, entityOffset, TCPServer.MAX_MESSAGE_BYTES);
		TCPServer.sendMessage(channel, outputBuffer);
		entityOffset += TCPServer.MAX_MESSAGE_BYTES;
	}
	outputBuffer.rewind();
	outputBuffer.put(entity, entityOffset, entity.length - entityOffset);
	outputBuffer.limit(entity.length - entityOffset);
	TCPServer.sendMessage(channel, outputBuffer);
}
 
开发者ID:roscisz,项目名称:KernelHive,代码行数:19,代码来源:DataPublisher.java

示例5: start0

import java.nio.channels.SocketChannel; //导入依赖的package包/类
private void start0() throws IOException {
    while (!closed) {

        processQueues();
        selector.select();

        if (selector.selectedKeys().isEmpty()) {
            processQueues();
        }

        for (Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext(); ) {
            SelectionKey key = i.next();
            i.remove();

            if (key.isConnectable()) {
                SocketChannel socketChannel = (SocketChannel) key.channel();
                socketChannel.finishConnect();
                LOG.info("SocketChannel connected.");
            }

            if (key.isReadable()) {
                this.socketChannelReader.readFromKey(key);
            }
        }
    }
}
 
开发者ID:yiding-he,项目名称:java-nio-test,代码行数:27,代码来源:SocketChannelClientHandler.java

示例6: handle

import java.nio.channels.SocketChannel; //导入依赖的package包/类
private void handle(SelectionKey key) {
	SocketChannel channel = (SocketChannel) key.channel();
	if (key.isConnectable()) {
		try {
			if (channel.finishConnect()) {
				//connect finish
				this.logger.info("[Connecter] finish connect " + channel.getRemoteAddress().toString());
				IoWorker worker = this.workers.get(workersIndex);
				worker.dispatch(new JobBean(channel, this.chanToParam.get(channel)));
				workersIndex = (workersIndex + 1) % workers.size();
			}
		} catch (IOException e) {
			this.logger.info("[Connecter] finish connect error : " + e.toString());
			ClientParam clientParam = this.chanToParam.get(channel);
			if (clientParam.getOnConnectError() != null) {
				clientParam.getOnConnectError().onConnectError(e);
			}
			this.chanToParam.remove(channel);
			try {
				channel.close();
			} catch (IOException e1) {
				// already close
			}
		}
	}
}
 
开发者ID:luohaha,项目名称:LightComm4J,代码行数:27,代码来源:Connector.java

示例7: release

import java.nio.channels.SocketChannel; //导入依赖的package包/类
/**
 * Expected to be used by the Poller to release resources on socket
 * close, errors etc.
 */
@Override
public void release(SocketChannel socket) {
    if (log.isDebugEnabled()) 
        log.debug("Iterating through our connections to release a socket channel:"+socket);
    boolean released = false;
    Iterator<java.util.Map.Entry<NioChannel, Processor<NioChannel>>> it = connections.entrySet().iterator();
    while (it.hasNext()) {
        java.util.Map.Entry<NioChannel, Processor<NioChannel>> entry = it.next();
        if (entry.getKey().getIOChannel()==socket) {
            it.remove();
            Processor<NioChannel> result = entry.getValue();
            result.recycle(true);
            unregister(result);
            released = true;
            break;
        }
    }
    if (log.isDebugEnabled()) 
        log.debug("Done iterating through our connections to release a socket channel:"+socket +" released:"+released);
}
 
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:25,代码来源:AjpNioProtocol.java

示例8: createOutgoingChannel

import java.nio.channels.SocketChannel; //导入依赖的package包/类
void createOutgoingChannel(final short p_nodeID) throws NetworkException {
    try {
        m_outgoingChannel = SocketChannel.open();
        m_outgoingChannel.configureBlocking(false);
        m_outgoingChannel.socket().setSoTimeout(0);
        m_outgoingChannel.socket().setTcpNoDelay(true);
        m_outgoingChannel.socket().setReceiveBufferSize(32);
        m_outgoingChannel.socket().setSendBufferSize(m_bufferSize);
        int sendBufferSize = m_outgoingChannel.socket().getSendBufferSize();
        if (sendBufferSize < m_bufferSize) {
            // #if LOGGER >= WARN
            LOGGER.warn("Send buffer size could not be set properly. Check OS settings! Requested: %d, actual: %d", m_bufferSize, sendBufferSize);
            // #endif /* LOGGER >= WARN */
        }

        m_outgoingChannel.connect(m_nodeMap.getAddress(p_nodeID));
    } catch (final IOException ignored) {
        throw new NetworkException("Creating outgoing channel failed");
    }
}
 
开发者ID:hhu-bsinfo,项目名称:dxram,代码行数:21,代码来源:NIOPipeOut.java

示例9: getAddress

import java.nio.channels.SocketChannel; //导入依赖的package包/类
@Override
public InetSocketAddress
getAddress()
{
	SocketChannel channel = ep.getSocketChannel();

	if ( channel != null ){

		Socket socket = channel.socket();

		if ( socket != null ){

			return((InetSocketAddress)socket.getLocalSocketAddress());
		}
	}

	return( null );
}
 
开发者ID:BiglySoftware,项目名称:BiglyBT,代码行数:19,代码来源:TransportStartpointTCP.java

示例10: SecureNioChannel

import java.nio.channels.SocketChannel; //导入依赖的package包/类
public SecureNioChannel(SocketChannel channel, SSLEngine engine, ApplicationBufferHandler bufHandler,
		NioSelectorPool pool) throws IOException {
	super(channel, bufHandler);
	this.sslEngine = engine;
	int appBufSize = sslEngine.getSession().getApplicationBufferSize();
	int netBufSize = sslEngine.getSession().getPacketBufferSize();
	// allocate network buffers - TODO, add in optional direct non-direct
	// buffers
	if (netInBuffer == null)
		netInBuffer = ByteBuffer.allocateDirect(netBufSize);
	if (netOutBuffer == null)
		netOutBuffer = ByteBuffer.allocateDirect(netBufSize);

	// selector pool for blocking operations
	this.pool = pool;

	// ensure that the application has a large enough read/write buffers
	// by doing this, we should not encounter any buffer overflow errors
	bufHandler.expand(bufHandler.getReadBuffer(), appBufSize);
	bufHandler.expand(bufHandler.getWriteBuffer(), appBufSize);
	reset();
}
 
开发者ID:how2j,项目名称:lazycat,代码行数:23,代码来源:SecureNioChannel.java

示例11: startNewConnection

import java.nio.channels.SocketChannel; //导入依赖的package包/类
@Override
public NonBlockingConnection startNewConnection() {
    try {
        SocketChannel socket = SocketChannel.open();
        NonBlockingConnection connection = new NonBlockingConnection(socket);

        // this connect is non-blocking and should always return false.
        boolean finished = ((SocketChannel) connection.getChannel()).connect(address);
        if (finished) {
            throw new IllegalStateException("async connect finished instantly?");
        }
        return connection;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:s-store,项目名称:s-store,代码行数:17,代码来源:ProtoRpcChannel.java

示例12: run

import java.nio.channels.SocketChannel; //导入依赖的package包/类
public void run() {
    SocketChannel socketChannel = null;

    while (accept) {

        try {
            socketChannel = _serverChannel.accept();
            if (!accept) {
                break;
            }
            // socket.setSoTimeout(getTimeout());
        } catch (final IOException e) {
            if (accept) {
                logger.log(Level.WARNING, "ServerNIO died: "
                        + e.getMessage(), e);
            }
            break;
        }
        handleConnection(socketChannel);
    }
}
 
开发者ID:fast-data-transfer,项目名称:fdt,代码行数:22,代码来源:ServerNIO.java

示例13: testStartConnection

import java.nio.channels.SocketChannel; //导入依赖的package包/类
/**
 * testStartConnection
 */
@Test
public void testStartConnection() throws Exception {
    System.err.println("testStartConnection()");
    for (final HStoreCoordinator m : this.coordinators) {
        // Check that the messenger state is correct
        assert (m.isStarted());

        // Check that the messenger's listener thread is running
        assert (m.getListenerThread().isAlive());

        // Check that we can connect to the messenger's listening port
        int port = m.getLocalMessengerPort();
        SocketChannel channel = SocketChannel.open();
        channel.connect(new InetSocketAddress(port));
        assert (channel.isConnected());
    } // FOR
}
 
开发者ID:s-store,项目名称:s-store,代码行数:21,代码来源:TestHStoreCoordinator.java

示例14: Connection

import java.nio.channels.SocketChannel; //导入依赖的package包/类
public Connection(SocketChannel channel, long lastContact) {
  this.channel = channel;
  this.lastContact = lastContact;
  this.data = null;
  this.dataLengthBuffer = ByteBuffer.allocate(4);
  this.unwrappedData = null;
  this.unwrappedDataLengthBuffer = ByteBuffer.allocate(4);
  this.socket = channel.socket();
  this.addr = socket.getInetAddress();
  if (addr == null) {
    this.hostAddress = "*Unknown*";
  } else {
    this.hostAddress = addr.getHostAddress();
  }
  this.remotePort = socket.getPort();
  this.responseQueue = new LinkedList<Call>();
  if (socketSendBufferSize != 0) {
    try {
      socket.setSendBufferSize(socketSendBufferSize);
    } catch (IOException e) {
      LOG.warn("Connection: unable to set socket send buffer size to " +
               socketSendBufferSize);
    }
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:26,代码来源:Server.java

示例15: removeSocket

import java.nio.channels.SocketChannel; //导入依赖的package包/类
protected void removeSocket(SocketChannel channel) {
  	if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
	logger.logDebug("Trying to remove cached socketChannel without key"
			+ this + " socketChannel = " + channel);
}
  	LinkedList<String> keys = new LinkedList<String>();
  	synchronized(socketTable) {
  		Set<Entry<String, SocketChannel>> e = socketTable.entrySet();
  		for(Entry<String, SocketChannel> entry : e ) {
  			SocketChannel sc = entry.getValue();
  			if(sc.equals(channel)) {
  				keys.add(entry.getKey());
  			}
  		}
  		for(String key : keys) {
  			if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
  				logger.logDebug("Removing cached socketChannel without key"
  						+ this + " socketChannel = " + channel + " key = " + key);
  			}
  			removeSocket(key);
  		}
  	}
  }
 
开发者ID:YunlongYang,项目名称:LightSIP,代码行数:24,代码来源:NIOHandler.java


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