java.nio.channels.SocketChannel Java Examples
The following examples show how to use
java.nio.channels.SocketChannel.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TcpClient2.java From game-server with MIT License | 6 votes |
/** * @throws IOException */ private void initialize() throws IOException { try { socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); selector = Selector.open(); socketChannel.register(selector, SelectionKey.OP_CONNECT); socketChannel.connect(new InetSocketAddress(hostIp, hostListenningPort)); } catch (Exception e) { e.printStackTrace(); } new TCPClientReadThread(this, selector, imei); }
Example #2
Source File: WebSocketClientFactory.java From WebSocket-for-Android with Apache License 2.0 | 6 votes |
protected SSLEngine newSslEngine(SocketChannel channel) throws IOException { SSLEngine sslEngine; if (channel != null) { String peerHost = channel.socket().getInetAddress().getHostAddress(); int peerPort = channel.socket().getPort(); sslEngine = _sslContextFactory.newSslEngine(peerHost, peerPort); } else { sslEngine = _sslContextFactory.newSslEngine(); } sslEngine.setUseClientMode(true); sslEngine.beginHandshake(); return sslEngine; }
Example #3
Source File: TCPFiberProxy.java From loom-fiber with MIT License | 6 votes |
@SuppressWarnings("resource") public static void main(String[] args) throws IOException { var server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(7777)); System.out.println("server bound to " + server.getLocalAddress()); var remote = SocketChannel.open(); remote.connect(new InetSocketAddress(InetAddress.getByName(Host.NAME), 7)); //remote.configureBlocking(false); System.out.println("accepting ..."); var client = server.accept(); //client.configureBlocking(false); var executor = Executors.newSingleThreadExecutor(); //var executor = ForkJoinPool.commonPool(); Thread.builder().virtual(executor).task(runnable(client, remote)).start(); Thread.builder().virtual(executor).task(runnable(remote, client)).start(); }
Example #4
Source File: ListenSyslog.java From nifi with Apache License 2.0 | 6 votes |
protected ChannelDispatcher createChannelReader(final ProcessContext context, final String protocol, final BlockingQueue<ByteBuffer> bufferPool, final BlockingQueue<RawSyslogEvent> events, final int maxConnections, final SSLContextService sslContextService, final Charset charset) throws IOException { final EventFactory<RawSyslogEvent> eventFactory = new RawSyslogEventFactory(); if (UDP_VALUE.getValue().equals(protocol)) { return new DatagramChannelDispatcher(eventFactory, bufferPool, events, getLogger()); } else { // if an SSLContextService was provided then create an SSLContext to pass down to the dispatcher SSLContext sslContext = null; SslContextFactory.ClientAuth clientAuth = null; if (sslContextService != null) { final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue(); sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.valueOf(clientAuthValue)); clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue); } final ChannelHandlerFactory<RawSyslogEvent<SocketChannel>, AsyncChannelDispatcher> handlerFactory = new SocketChannelHandlerFactory<>(); return new SocketChannelDispatcher(eventFactory, handlerFactory, bufferPool, events, getLogger(), maxConnections, sslContext, clientAuth, charset); } }
Example #5
Source File: FIXAcceptor.java From parity with Apache License 2.0 | 6 votes |
Session accept() { try { SocketChannel fix = serverChannel.accept(); if (fix == null) return null; try { fix.setOption(StandardSocketOptions.TCP_NODELAY, true); fix.configureBlocking(false); return new Session(orderEntry, fix, config, instruments); } catch (IOException e1) { fix.close(); return null; } } catch (IOException e2) { return null; } }
Example #6
Source File: RemotingUtil.java From DDMQ with Apache License 2.0 | 6 votes |
public static SocketChannel connect(SocketAddress remote, final int timeoutMillis) { SocketChannel sc = null; try { sc = SocketChannel.open(); sc.configureBlocking(true); sc.socket().setSoLinger(false, -1); sc.socket().setTcpNoDelay(true); sc.socket().setReceiveBufferSize(1024 * 64); sc.socket().setSendBufferSize(1024 * 64); sc.socket().connect(remote, timeoutMillis); sc.configureBlocking(false); return sc; } catch (Exception e) { if (sc != null) { try { sc.close(); } catch (IOException e1) { e1.printStackTrace(); } } } return null; }
Example #7
Source File: SelectorManager.java From IoTgo_Android_App with MIT License | 6 votes |
/** Register a channel * @param channel * @param att Attached Object */ public void register(SocketChannel channel, Object att) { // The ++ increment here is not atomic, but it does not matter. // so long as the value changes sometimes, then connections will // be distributed over the available sets. int s=_set++; if (s<0) s=-s; s=s%_selectSets; SelectSet[] sets=_selectSet; if (sets!=null) { SelectSet set=sets[s]; set.addChange(channel,att); set.wakeup(); } }
Example #8
Source File: SelectorThread.java From L2jBrasil with GNU General Public License v3.0 | 6 votes |
private final void finishConnection(final SelectionKey key, final MMOConnection<T> con) { try { ((SocketChannel) key.channel()).finishConnect(); } catch (IOException e) { con.getClient().onForcedDisconnection(); closeConnectionImpl(key, con); } // key might have been invalidated on finishConnect() if (key.isValid()) { key.interestOps(key.interestOps() | SelectionKey.OP_READ); key.interestOps(key.interestOps() & ~SelectionKey.OP_CONNECT); } }
Example #9
Source File: AbstractSession.java From Mycat2 with GNU General Public License v3.0 | 6 votes |
/** * todo: check that code is right * * @return */ public boolean checkOpen() { SocketChannel channel = channel(); boolean open = !hasClosed() && channel.isOpen() && channel.isConnected(); if (open) { ByteBuffer allocate = ByteBuffer.allocate(0); boolean close; try { close = -1 == channel.read(allocate); } catch (IOException e) { close = true; } if (close) { this.close(false, "check open"); return false; } return true; } return false; }
Example #10
Source File: WireTcpHandlerTest.java From Chronicle-Network with Apache License 2.0 | 6 votes |
@Test public void testProcess() throws IOException { // TODO FIX AbstractReferenceCounted.disableReferenceTracing(); try (@NotNull EventLoop eg = new EventGroup(true)) { eg.start(); TCPRegistry.createServerSocketChannelFor(desc); @NotNull AcceptorEventHandler eah = new AcceptorEventHandler(desc, simpleTcpEventHandlerFactory(EchoRequestHandler::new, wireType), VanillaNetworkContext::new); eg.addHandler(eah); SocketChannel sc = TCPRegistry.createSocketChannel(desc); sc.configureBlocking(false); // testThroughput(sc); testLatency(desc, wireType, sc); eg.stop(); TcpChannelHub.closeAllHubs(); } }
Example #11
Source File: HTTPRawSampler.java From jmeter-plugins with Apache License 2.0 | 6 votes |
private void sendFile(String filename, SocketChannel sock) throws IOException { if (filename.isEmpty()) { return; } FileInputStream is = new FileInputStream(new File(filename)); FileChannel source = is.getChannel(); ByteBuffer sendBuf = ByteBuffer.allocateDirect(fileSendingChunk); while (source.read(sendBuf) > 0) { sendBuf.flip(); if (log.isDebugEnabled()) { log.debug("Sending " + sendBuf); } sock.write(sendBuf); sendBuf.rewind(); } source.close(); }
Example #12
Source File: ProxyReactorThread.java From Mycat2 with GNU General Public License v3.0 | 6 votes |
/** * 该方法仅Reactor自身创建的主动连接使用 */ @SuppressWarnings("unchecked") protected void processConnectKey(SelectionKey curKey) throws IOException { T session = (T) curKey.attachment(); setCurSession(session); SocketChannel channel = (SocketChannel) curKey.channel(); NIOHandler curNIOHandler = session.getCurNIOHandler(); if (curNIOHandler instanceof BackendNIOHandler) { BackendNIOHandler handler = (BackendNIOHandler) curNIOHandler; try { if (channel.finishConnect()) { handler.onConnect(curKey, session, true, null); }else { handler.onConnect(curKey, session, false, new ConnectException()); } } catch (Exception e) { handler.onConnect(curKey, session, false, e); } } }
Example #13
Source File: SocketChannelStream.java From baratine with GNU General Public License v2.0 | 6 votes |
/** * Initialize the SocketStream with a new Socket. * * @param s the new socket. */ public void init(SocketChannel s) { _s = s; try { s.setOption(StandardSocketOptions.TCP_NODELAY, true); } catch (Exception e) { e.printStackTrace();; } //_is = null; //_os = null; _needsFlush = false; _readBuffer.clear().flip(); _writeBuffer.clear(); }
Example #14
Source File: NonBlockingFetcher.java From SEAL with Apache License 2.0 | 6 votes |
private static boolean doRead(SocketChannel channel, Work work) throws IOException { buffer.clear(); boolean done = false; int numBytesRead = channel.read(buffer); if (numBytesRead == -1) { work.success = true; done = true; } else if (numBytesRead > 0) { buffer.flip(); int bufSizeRemaining = work.buffer.remaining(); // see if the bytes read can fit into the buffer if (bufSizeRemaining >= numBytesRead) { // buffer has enough space left work.buffer.put(buffer); } else if (bufSizeRemaining > 0) { // buffer doesn't have enough space, will discard bytes that don't fit buffer.limit(bufSizeRemaining); work.buffer.put(buffer); } } return done; }
Example #15
Source File: DefaultIOErrorHandler.java From Mycat-Balance with Apache License 2.0 | 6 votes |
@Override public void handle(SocketChannel socketChannel, IOException e, ChannelContext channelContext, String customMsg) { String reasonString = ""; if (channelContext != null) { StringBuilder buffer = new StringBuilder(); String _customMsg = customMsg == null ? "IOException" : customMsg; buffer.append(channelContext.getId() + " " + _customMsg); if (e != null) { log.error(buffer.toString(), e); reasonString = e.getMessage(); } else { log.error(buffer.toString()); } } NioUtils.remove(channelContext, reasonString); }
Example #16
Source File: SslEngineStateMachine.java From Chronicle-Network with Apache License 2.0 | 6 votes |
void initialise(SSLContext ctx, SocketChannel channel) { try { channel.configureBlocking(false); engine = ctx.createSSLEngine(); engine.setUseClientMode(!isAcceptor); if (isAcceptor) { engine.setNeedClientAuth(true); } outboundApplicationData = ByteBuffer.allocateDirect(engine.getSession().getApplicationBufferSize()); outboundEncodedData = ByteBuffer.allocateDirect(engine.getSession().getPacketBufferSize()); inboundApplicationData = ByteBuffer.allocateDirect(engine.getSession().getApplicationBufferSize()); inboundEncodedData = ByteBuffer.allocateDirect(engine.getSession().getPacketBufferSize()); // eliminates array creation on each call to SSLEngine.wrap() precomputedWrapArray = new ByteBuffer[]{outboundApplicationData}; precomputedUnwrapArray = new ByteBuffer[]{inboundApplicationData}; new Handshaker().performHandshake(engine, channel); } catch (IOException e) { throw new RuntimeException("Unable to perform handshake at " + Instant.now(), e); } }
Example #17
Source File: TcpBulkClient.java From netcrusher-java with Apache License 2.0 | 5 votes |
public static TcpBulkClient forAddress(String name, InetSocketAddress address, long limit) throws IOException { SocketChannel channel = SocketChannel.open(); channel.configureBlocking(true); channel.connect(address); return forSocket(name, channel, limit); }
Example #18
Source File: ServantClient.java From TarsJava with BSD 3-Clause "New" or "Revised" License | 5 votes |
public void setTcpNoDelay(boolean on) { this.tcpNoDelay = on; if (this.session != null && this.session instanceof TCPSession) { try { ((SocketChannel) ((TCPSession) this.session).getChannel()).socket().setTcpNoDelay(on); } catch (Exception ex) { logger.error(ex.getLocalizedMessage()); } } }
Example #19
Source File: TcpSocket.java From swim with Apache License 2.0 | 5 votes |
TcpSocket(InetSocketAddress localAddress, InetSocketAddress remoteAddress, SocketChannel channel, IpSettings ipSettings, boolean isClient) { this.localAddress = localAddress; this.remoteAddress = remoteAddress; this.channel = channel; this.ipSettings = ipSettings; this.status = isClient ? CLIENT : SERVER; final TcpSettings tcpSettings = ipSettings.tcpSettings(); this.readBuffer = ByteBuffer.allocate(tcpSettings.readBufferSize()); this.writeBuffer = ByteBuffer.allocate(tcpSettings.writeBufferSize()); ((Buffer) this.writeBuffer).position(this.writeBuffer.capacity()); this.inputBuffer = Binary.inputBuffer(this.readBuffer); this.outputBuffer = Binary.outputBuffer(this.writeBuffer); }
Example #20
Source File: IOMultiplexEchoServer.java From new-bull with MIT License | 5 votes |
private void onAccept(SelectionKey key) throws IOException { SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); System.out.println("Got newClient : " + socketChannel.getRemoteAddress()); Client newClient = new Client(socketChannel); socketChannel.register(selector, SelectionKey.OP_READ, newClient); }
Example #21
Source File: SocketChannelDataLink.java From libcommon with Apache License 2.0 | 5 votes |
/** * このClientのアドレスを取得 * @return */ public synchronized String getAddress() { final Socket socket = (mChannel instanceof SocketChannel) ? ((SocketChannel)mChannel).socket() : null; final InetAddress address = socket != null ? socket.getInetAddress() : null; return address != null ? address.getHostAddress() : null; }
Example #22
Source File: TCPConnection.java From gnirehtet with Apache License 2.0 | 5 votes |
private SocketChannel createChannel() throws IOException { logi(TAG, "Open"); SocketChannel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.connect(getRewrittenDestination()); return socketChannel; }
Example #23
Source File: TestTunnelWithArbitraryTCPTraffic.java From incubator-gobblin with Apache License 2.0 | 5 votes |
@Test(enabled=false, timeOut = 15000) public void testDirectConnectionToEchoServer() throws IOException { SocketChannel client = SocketChannel.open(); try { client.connect(new InetSocketAddress("localhost", doubleEchoServer.getServerSocketPort())); writeToSocket(client, "Knock\n".getBytes()); String response = readFromSocket(client); client.close(); assertEquals(response, "Knock Knock\n"); } finally { client.close(); } }
Example #24
Source File: NClient.java From chat with MIT License | 5 votes |
public void init() throws IOException { selector = Selector.open(); InetSocketAddress isa = new InetSocketAddress("127.0.0.1", 3000); sc = SocketChannel.open(isa); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); new ClientThread().start(); @SuppressWarnings("resource") Scanner scan = new Scanner(System.in); while (scan.hasNextLine()) { sc.write(charset.encode(scan.nextLine())); } }
Example #25
Source File: StandardCommsSession.java From nifi with Apache License 2.0 | 5 votes |
public StandardCommsSession(final String hostname, final int port, final int timeoutMillis) throws IOException { socketChannel = SocketChannel.open(); socketChannel.socket().connect(new InetSocketAddress(hostname, port), timeoutMillis); socketChannel.configureBlocking(false); in = new SocketChannelInputStream(socketChannel); bufferedIn = new InterruptableInputStream(new BufferedInputStream(in)); out = new SocketChannelOutputStream(socketChannel); bufferedOut = new InterruptableOutputStream(new BufferedOutputStream(out)); this.hostname = hostname; this.port = port; }
Example #26
Source File: SelectorManager.java From IoTgo_Android_App with MIT License | 5 votes |
private SelectChannelEndPoint createEndPoint(SocketChannel channel, SelectionKey sKey) throws IOException { SelectChannelEndPoint endp = newEndPoint(channel,this,sKey); LOG.debug("created {}",endp); endPointOpened(endp); _endPoints.put(endp,this); return endp; }
Example #27
Source File: Driver.java From qpid-proton-j with Apache License 2.0 | 5 votes |
ChannelHandler(SocketChannel socket, int ops, Transport transport) throws IOException { this.socket = socket; socket.configureBlocking(false); key = socket.register(selector, ops, this); this.transport = transport; transport.setContext(this); }
Example #28
Source File: Talk.java From SuitAgent with Apache License 2.0 | 5 votes |
/** * 传递客户端连接的SocketChannel,然后用非阻塞模式进行读事件和写事件的相应 * * @param socketChannel 客户端SocketChannel * @throws IOException */ public Talk(SocketChannel socketChannel,Agent agent) throws IOException { this.socketChannel = socketChannel; selector = Selector.open(); ByteBuffer buffer = ByteBuffer.allocate(2048); //创建用于存放用户发来的数据的缓冲区,并将其作为通道附件的形式进行保存 socketChannel.configureBlocking(false);//设置非阻塞模式 //向Selector注册读就绪事件和写就绪事件,以便响应客户端发来的数据 socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, buffer); this.agent = agent; }
Example #29
Source File: AbstractHTTPServer.java From swift-k with Apache License 2.0 | 5 votes |
public void addChannel(SocketChannel s) throws ClosedChannelException { synchronized (channels) { channels.put(s, new ConnectionState(this, s.socket(), server)); newChannels.add(s); selector.wakeup(); } }
Example #30
Source File: NIOConnector.java From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License | 5 votes |
@SuppressWarnings("unchecked") private void finishConnect(SelectionKey key, Object att) { ClosableConnection c = (ClosableConnection) att; try { //做原生NIO连接是否完成的判断和操作 if (finishConnect(c, (SocketChannel) c.getSocketChannel())) { clearSelectionKey(key); //c.setId( ConnectIdGenerator.getINSTNCE().getId() ); //与特定NIOReactor绑定监听读写 NIOReactor reactor = reactorPool.getNextReactor(); reactor.postRegister(c); } } catch (Throwable e) { String host = ""; int port = 0; if (c != null) { host = c.getHost(); port = c.getPort(); } LOGGER.warn("caught err : host=" + host + ":" + port, e); //异常, 将key清空 clearSelectionKey(key); c.close(e.toString()); c.getHandler().onConnectFailed(c, new Exception(e.getMessage())); } }