Java Code Examples for java.nio.channels.SocketChannel#configureBlocking()
The following examples show how to use
java.nio.channels.SocketChannel#configureBlocking() .
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: SSLCommsSession.java From nifi with Apache License 2.0 | 6 votes |
public SSLCommsSession(final SSLContext sslContext, final String hostname, final int port, final int timeoutMillis) throws IOException { final SocketChannel socketChannel = SocketChannel.open(); socketChannel.socket().connect(new InetSocketAddress(hostname, port), timeoutMillis); socketChannel.configureBlocking(false); sslSocketChannel = new SSLSocketChannel(sslContext, socketChannel,true); in = new SSLSocketChannelInputStream(sslSocketChannel); bufferedIn = new BufferedInputStream(in); out = new SSLSocketChannelOutputStream(sslSocketChannel); bufferedOut = new BufferedOutputStream(out); this.sslContext = sslContext; this.hostname = hostname; this.port = port; }
Example 2
Source File: IpStation.java From swim with Apache License 2.0 | 6 votes |
@Override default IpSocketRef connectTcp(InetSocketAddress remoteAddress, IpSocket socket, IpSettings ipSettings) { try { final Station station = station(); final SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); ipSettings.configure(channel.socket()); final boolean connected = channel.connect(remoteAddress); final InetSocketAddress localAddress = (InetSocketAddress) channel.socket().getLocalSocketAddress(); final TcpSocket context = new TcpSocket(localAddress, remoteAddress, channel, ipSettings, true); context.become(socket); if (connected) { station.transport(context, FlowControl.WAIT); context.didConnect(); } else { context.willConnect(); station.transport(context, FlowControl.CONNECT); } return context; } catch (IOException | UnresolvedAddressException error) { throw new StationException(remoteAddress.toString(), error); } }
Example 3
Source File: RemotingUtil.java From dts 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 4
Source File: NIOAcceptor.java From Mycat2 with GNU General Public License v3.0 | 6 votes |
private void accept() { SocketChannel channel = null; try { channel = serverChannel.accept(); channel.configureBlocking(false); FrontendConnection c = factory.make(channel); c.setAccepted(true); c.setId(ID_GENERATOR.getId()); NIOProcessor processor = (NIOProcessor) MycatServer.getInstance() .nextProcessor(); c.setProcessor(processor); NIOReactor reactor = reactorPool.getNextReactor(); reactor.postRegister(c); } catch (Exception e) { LOGGER.warn(getName(), e); closeChannel(channel); } }
Example 5
Source File: RemotingUtil.java From TakinRPC 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 6
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 7
Source File: GfxdTSocket.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * Constructor that takes an already created socket. * * @param socket * Already created socket object * @param params * Socket parameters including buffer sizes and keep-alive settings * @param props * the system properties instance to use and initialize global socket * options like keepalive and buffer sizes that are not set in params * * @throws TTransportException * if there is an error setting up the streams */ public GfxdTSocket(SocketChannel socketChannel, boolean blocking, int timeout, SocketParameters params, SystemProperties props) throws TTransportException { this.socketChannel = socketChannel; if (!socketChannel.isConnected()) throw new TTransportException(TTransportException.NOT_OPEN, "Socket must already be connected"); try { socketChannel.configureBlocking(blocking); setProperties(socketChannel.socket(), timeout, params, props); this.inputStream = UnsafeHolder.newChannelBufferFramedInputStream( socketChannel, this.inputBufferSize); this.outputStream = UnsafeHolder.newChannelBufferOutputStream( socketChannel, this.outputBufferSize); this.framedWrites = false; } catch (IOException ioe) { close(); throw new TTransportException(TTransportException.NOT_OPEN, ioe); } }
Example 8
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 9
Source File: Server.java From twister2 with Apache License 2.0 | 5 votes |
@Override public void handleAccept(SelectableChannel ch) { try { SocketChannel socketChannel = serverSocketChannel.accept(); LOG.log(Level.FINE, "Accepted connection: " + socketChannel); if (socketChannel == null) { LOG.log(Level.WARNING, "Accepted connection but SocketChannel is null: " + socketChannel); } else { socketChannel.configureBlocking(false); socketChannel.socket().setTcpNoDelay(true); BaseNetworkChannel channel; if (fixedBuffers) { channel = new FixedBufferChannel(config, progress, this, socketChannel, channelHandler); } else { channel = new DynamicBufferChannel(config, progress, this, socketChannel, channelHandler); } channel.enableReading(); channel.enableWriting(); connectedChannels.put(socketChannel, channel); channelHandler.onConnect(socketChannel); } } catch (IOException e) { LOG.log(Level.SEVERE, "Error while accepting a new connection ", e); } }
Example 10
Source File: NIOServer.java From JavaBase with MIT License | 5 votes |
private void register(Selector selector, ServerSocketChannel server, SelectionKey sk) throws IOException { //调用accept方法,产生服务器端的SocketChannel SocketChannel sc = server.accept(); sc.configureBlocking(false);//NIO模式 sc.register(selector, SelectionKey.OP_READ);//注册到selector上 sk.interestOps(SelectionKey.OP_ACCEPT);//将sk对应的Channel设置成准备接受其他请求 }
Example 11
Source File: RealAndroidDevice.java From buck with Apache License 2.0 | 5 votes |
private SocketChannel getSyncService() throws Exception { // Create a socket and send the necessary requests to adb daemon SocketChannel chan = SocketChannel.open(AndroidDebugBridge.getSocketAddress()); // Set a timeout for the blocking channel chan.socket().setSoTimeout(DEFAULT_TIMEOUT); // Set the channel to be blocking chan.configureBlocking(true); String msg = "host:transport:" + device.getSerialNumber(); byte[] device_query = formAdbRequest(msg); // req = length + command writeAllToChannel(chan, ByteBuffer.wrap(device_query)); byte[] resp = readResp(chan, 4); if (!isOkay(resp)) { throw new HumanReadableException( "ADB daemon rejected switching connection to " + device.getSerialNumber()); } byte[] sync_req = formAdbRequest("sync:"); ByteBuffer b = ByteBuffer.wrap(sync_req); writeAllToChannel(chan, b); if (!isOkay(readResp(chan, 4))) { throw new HumanReadableException( "ADB daemon rejected starting sync service to " + device.getSerialNumber()); } return chan; }
Example 12
Source File: BackendConnectionFactory.java From dble with GNU General Public License v2.0 | 5 votes |
protected NetworkChannel openSocketChannel(boolean isAIO) throws IOException { if (isAIO) { return AsynchronousSocketChannel.open(DbleServer.getInstance().getNextAsyncChannelGroup()); } else { SocketChannel channel = null; channel = SocketChannel.open(); channel.configureBlocking(false); return channel; } }
Example 13
Source File: ServerSockerChannelTest.java From jdk-source-analysis with Apache License 2.0 | 5 votes |
public Handler(Selector selector, SocketChannel channel) throws IOException { socket = channel; channel.configureBlocking(false); selectionKey = socket.register(selector, 0); selectionKey.attach(this); selectionKey.interestOps(SelectionKey.OP_READ); selector.wakeup(); }
Example 14
Source File: BlinkClient.java From Blink with Artistic License 2.0 | 5 votes |
public boolean connect(SocketAddress address) { mAddress = address; try { SocketChannel channel = SocketChannel.open(mAddress); boolean connected = channel.isConnected(); if (connected) { channel.configureBlocking(false); start(channel); } return connected; } catch (IOException e) { e.printStackTrace(); return false; } }
Example 15
Source File: ExternalSessionFactory.java From james-project with Apache License 2.0 | 5 votes |
@Override public Session newSession(Continuation continuation) throws Exception { InetSocketAddress address = getAddress(); monitor.note("Connecting to " + address.getHostName() + ":" + address.getPort()); final SocketChannel channel = SocketChannel.open(address); channel.configureBlocking(false); return new ExternalSession(channel, monitor, shabang); }
Example 16
Source File: Acceptor.java From aion-germany with GNU General Public License v3.0 | 4 votes |
/** * Method called by Accept <code>Dispatcher</code> <code>Selector</code> * when socket<br> * connects to <code>ServerSocketChannel</code> listening for * connections.<br> * New instance of <code>AConnection</code> will be created by * <code>ConnectionFactory</code>,<br> * socket representing accepted connection will be register into<br> * one of ReadWrite <code>Dispatchers</code> * <code>Selector as ready for io read operations.<br> * * @param key * <code>SelectionKey</code> representing * <code>ServerSocketChannel</code> that is accepting<br> * new socket connection. * * @throws IOException * @see com.aionemu.commons.network.Dispatcher * @see java.nio.channels.ServerSocketChannel * @see java.nio.channels.SelectionKey * @see java.nio.channels.SocketChannel * @see java.nio.channels.Selector * @see com.aionemu.commons.network.AConnection * @see com.aionemu.commons.network.ConnectionFactory */ public final void accept(SelectionKey key) throws IOException { /** * For an accept to be pending the channel must be a server socket * channel. */ ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); /** Accept the connection and make it non-blocking */ SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); Dispatcher dispatcher = nioServer.getReadWriteDispatcher(); AConnection con = factory.create(socketChannel, dispatcher); if (con == null) { return; } // register dispatcher.register(socketChannel, SelectionKey.OP_READ, con); // notify initialized :) con.initialized(); }
Example 17
Source File: LotsOfCancels.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 4 votes |
private void handleClients() throws Exception { int selectCount = 0; while (true) { int createdCount = 0; synchronized (this) { if (connectionsNeeded > 0) { while (connectionsNeeded > 0 && createdCount < 20) { connectionsNeeded--; createdCount++; totalCreated++; SocketChannel channel = SocketChannel.open(); channel.configureBlocking(false); channel.connect(address); if (!channel.finishConnect()) { channel.register(selector, SelectionKey.OP_CONNECT); } } log("Started total of " + totalCreated + " client connections"); Thread.sleep(200); } } if (createdCount > 0) { selector.selectNow(); } else { selectCount++; long startTime = System.nanoTime(); selector.select(); long duration = durationMillis(startTime); log("Exited clientSelector.select(), loop #" + selectCount + ", duration = " + duration + "ms"); } int keyCount = -1; Iterator<SelectionKey> keys = selector.selectedKeys().iterator(); while (keys.hasNext()) { SelectionKey key = keys.next(); synchronized (key) { keyCount++; keys.remove(); if (!key.isValid()) { log("Ignoring client key #" + keyCount); continue; } int readyOps = key.readyOps(); if (readyOps == SelectionKey.OP_CONNECT) { key.interestOps(0); ((SocketChannel) key.channel()).finishConnect(); } else { log("readyOps() on client key #" + keyCount + " returned " + readyOps); } } } } }
Example 18
Source File: SenderKeyHandler.java From cacheonix-core with GNU Lesser General Public License v2.1 | 4 votes |
/** * Begins connecting to a given inet address. * * @param initAddressesToTry if the connect attempt must start from the beginning of the list of available * addresses. */ private void beginConnecting(final boolean initAddressesToTry) { // Re-populate addresses to try if needed if (initAddressesToTry) { addressesToTry.clear(); addressesToTry.addAll(Arrays.asList(receiverAddress.getAddresses())); } //noinspection ControlFlowStatementWithoutBraces // if (LOG.isDebugEnabled()) { // LOG.debug("Beginning to connect to " + receiverNodeAddress + ", addresses to try: " + addressesToTry); // NOPMD // } // Go through available addresses to try. while (!addressesToTry.isEmpty()) { // Try next address final InetAddress address = addressesToTry.removeFirst(); SocketChannel socketChannel = null; try { final int tcpPort = receiverAddress.getTcpPort(); final InetSocketAddress inetSocketAddress = new InetSocketAddress(address, tcpPort); socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.register(selector(), OP_CONNECT, this); socketChannel.connect(inetSocketAddress); // Register activity because it is possible that the request to begin // connection came from a dormant sender that was disconnected because // of inactivity. registerActivity(); // An attempt to begin to connect was successful, // switch to connecting state state = CONNECTING; // Return immediately return; } catch (final IOException e) { //noinspection ControlFlowStatementWithoutBraces if (LOG.isDebugEnabled()) LOG.debug("e: " + e, e); // NOPMD // // Failed to begin to connect, will try next // address if any // IOUtils.closeHard(socketChannel); } } // The fact that we are here means we failed to // initiate a connect at all available addresses. // Switch to initial state until someone // enqueues a message to send. state = INIT; // Respond as a failure to all messages respondToAllWithFailure("Cannot connect to receiver at " + receiverAddress); }
Example 19
Source File: AdbHelper.java From javaide with GNU General Public License v3.0 | 4 votes |
/** * Retrieve the frame buffer from the device with the given timeout. A timeout of 0 indicates * that it will wait forever. * * @throws TimeoutException in case of timeout on the connection. * @throws AdbCommandRejectedException if adb rejects the command * @throws IOException in case of I/O error on the connection. */ static RawImage getFrameBuffer(InetSocketAddress adbSockAddr, Device device, long timeout, TimeUnit unit) throws TimeoutException, AdbCommandRejectedException, IOException { RawImage imageParams = new RawImage(); byte[] request = formAdbRequest("framebuffer:"); //$NON-NLS-1$ byte[] nudge = { 0 }; byte[] reply; SocketChannel adbChan = null; try { adbChan = SocketChannel.open(adbSockAddr); adbChan.configureBlocking(false); // if the device is not -1, then we first tell adb we're looking to talk // to a specific device setDevice(adbChan, device); write(adbChan, request); AdbResponse resp = readAdbResponse(adbChan, false /* readDiagString */); if (!resp.okay) { throw new AdbCommandRejectedException(resp.message); } // first the protocol version. reply = new byte[4]; read(adbChan, reply); ByteBuffer buf = ByteBuffer.wrap(reply); buf.order(ByteOrder.LITTLE_ENDIAN); int version = buf.getInt(); // get the header size (this is a count of int) int headerSize = RawImage.getHeaderSize(version); // read the header reply = new byte[headerSize * 4]; read(adbChan, reply); buf = ByteBuffer.wrap(reply); buf.order(ByteOrder.LITTLE_ENDIAN); // fill the RawImage with the header if (!imageParams.readHeader(version, buf)) { Log.e("Screenshot", "Unsupported protocol: " + version); return null; } Log.d("ddms", "image params: bpp=" + imageParams.bpp + ", size=" + imageParams.size + ", width=" + imageParams.width + ", height=" + imageParams.height); write(adbChan, nudge); reply = new byte[imageParams.size]; read(adbChan, reply, imageParams.size, unit.toMillis(timeout)); imageParams.data = reply; } finally { if (adbChan != null) { adbChan.close(); } } return imageParams; }
Example 20
Source File: RacyDeregister.java From jdk8u-jdk with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { InetAddress addr = InetAddress.getByName(null); ServerSocketChannel sc = ServerSocketChannel.open(); sc.socket().bind(new InetSocketAddress(addr, 0)); SocketChannel.open(new InetSocketAddress(addr, sc.socket().getLocalPort())); SocketChannel accepted = sc.accept(); accepted.configureBlocking(false); SocketChannel.open(new InetSocketAddress(addr, sc.socket().getLocalPort())); SocketChannel accepted2 = sc.accept(); accepted2.configureBlocking(false); final Selector sel = Selector.open(); SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ); final SelectionKey[] key = new SelectionKey[]{ accepted.register(sel, SelectionKey.OP_READ)}; // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE new Thread() { public void run() { try { for (int k = 0; k < 15; k++) { for (int i = 0; i < 10000; i++) { synchronized (notifyLock) { synchronized (selectorLock) { sel.wakeup(); key[0].interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); } notified = false; long beginTime = System.currentTimeMillis(); while (true) { notifyLock.wait(5000); if (notified) { break; } long endTime = System.currentTimeMillis(); if (endTime - beginTime > 5000) { succTermination = false; // wake up main thread doing select() sel.wakeup(); return; } } } } } succTermination = true; // wake up main thread doing select() sel.wakeup(); } catch (Exception e) { System.out.println(e); succTermination = true; // wake up main thread doing select() sel.wakeup(); } } }.start(); // main thread will be doing registering/deregistering with the sel while (true) { sel.select(); if (Boolean.TRUE.equals(succTermination)) { System.out.println("Test passed"); sel.close(); sc.close(); break; } else if (Boolean.FALSE.equals(succTermination)) { System.out.println("Failed to pass the test"); sel.close(); sc.close(); throw new RuntimeException("Failed to pass the test"); } synchronized (selectorLock) { } if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) { synchronized (notifyLock) { notified = true; notifyLock.notify(); key[0].cancel(); sel.selectNow(); key2 = accepted2.register(sel, SelectionKey.OP_READ); key[0] = accepted.register(sel, SelectionKey.OP_READ); } } key2.cancel(); sel.selectedKeys().clear(); } }