org.apache.mina.core.future.WriteFuture Java Examples
The following examples show how to use
org.apache.mina.core.future.WriteFuture.
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: TesterSink.java From streamsx.topology with Apache License 2.0 | 6 votes |
@Override protected boolean processBatch(Queue<BatchedTuple> batch) throws Exception { List<WriteFuture> futures = new ArrayList<>(batch.size()); for (BatchedTuple bt : batch) { int portIndex = bt.getStream().getPortNumber(); TCPTestClient client = clients[portIndex]; BinaryEncoding be = encoders[portIndex]; byte[] tupleData = new byte[(int) be.getEncodedSize(bt.getTuple())]; be.encodeTuple(bt.getTuple(), ByteBuffer.wrap(tupleData)); TestTuple tt = new TestTuple(portIndex, tupleData); futures.add(client.writeTuple(tt)); } for (WriteFuture future : futures) { future.await(); } return false; }
Example #2
Source File: WriteRequestFilter.java From neoscada with Eclipse Public License 1.0 | 6 votes |
@Override public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { final IoEvent e = new IoEvent(IoEventType.WRITE, session, writeRequest); if (queueHandler.accept(this, e)) { nextFilter.filterWrite(session, writeRequest); WriteFuture writeFuture = writeRequest.getFuture(); if (writeFuture == null) { return; } // We can track the write request only when it has a future. queueHandler.offered(this, e); writeFuture.addListener(new IoFutureListener<WriteFuture>() { public void operationComplete(WriteFuture future) { queueHandler.polled(WriteRequestFilter.this, e); } }); } }
Example #3
Source File: AbstractIoService.java From neoscada with Eclipse Public License 1.0 | 6 votes |
/** * {@inheritDoc} */ public final Set<WriteFuture> broadcast(Object message) { // Convert to Set. We do not return a List here because only the // direct caller of MessageBroadcaster knows the order of write // operations. final List<WriteFuture> futures = IoUtil.broadcast(message, getManagedSessions().values()); return new AbstractSet<WriteFuture>() { @Override public Iterator<WriteFuture> iterator() { return futures.iterator(); } @Override public int size() { return futures.size(); } }; }
Example #4
Source File: NetManager.java From jane with GNU Lesser General Public License v3.0 | 6 votes |
/** * 发送对象的底层入口. 可带监听器,并返回WriteFuture */ public static WriteFuture write(IoSession session, Object obj, IoFutureListener<?> listener) { if (session.isClosing() || obj == null) return null; IoFilterChain ifc = session.getFilterChain(); WriteFuture wf = new DefaultWriteFuture(session); if (listener != null) wf.addListener(listener); DefaultWriteRequest dwr = new DefaultWriteRequest(obj, wf); synchronized (session) { ifc.fireFilterWrite(dwr); } return wf; }
Example #5
Source File: SslFilter.java From neoscada with Eclipse Public License 1.0 | 6 votes |
private WriteFuture initiateClosure(NextFilter nextFilter, IoSession session) throws SSLException { SslHandler handler = getSslSessionHandler(session); // if already shut down if (!handler.closeOutbound()) { return DefaultWriteFuture.newNotWrittenFuture(session, new IllegalStateException( "SSL session is shut down already.")); } // there might be data to write out here? WriteFuture future = handler.writeNetBuffer(nextFilter); if (future == null) { future = DefaultWriteFuture.newWrittenFuture(session); } if (handler.isInboundDone()) { handler.destroy(); } if (session.containsAttribute(USE_NOTIFICATION)) { handler.scheduleMessageReceived(nextFilter, SESSION_UNSECURED); } return future; }
Example #6
Source File: SslFilter.java From jane with GNU Lesser General Public License v3.0 | 6 votes |
/** * Stops the SSL session by sending TLS <tt>close_notify</tt> message to initiate TLS closure. * * @param session the {@link IoSession} to initiate TLS closure * @return The Future for the initiated closure * @throws SSLException if failed to initiate TLS closure */ public WriteFuture stopSsl(IoSession session, boolean needFuture) throws Exception { SslHandler sslHandler = getSslSessionHandler(session); try { WriteFuture future; synchronized (sslHandler) { future = initiateClosure(sslHandler.getNextFilter(), session, needFuture); } sslHandler.flushScheduledEvents(); return future; } catch (SSLException se) { sslHandler.release(); throw se; } }
Example #7
Source File: GameClient.java From gameserver with Apache License 2.0 | 6 votes |
/** * Send a message to server. * @param msg */ public void sendMessageToServer(XinqiMessage msg) { try { resourceLock.lock(); if ( session == null || !session.isConnected() ) { disconnectFromServer(); connectToServer(); } WriteFuture future = session.write(msg); future.addListener(statListener); } catch (Throwable t) { if ( log.isDebugEnabled() ) { log.debug(t, t); } } finally { resourceLock.unlock(); } }
Example #8
Source File: MINAServerSession.java From sailfish-core with Apache License 2.0 | 6 votes |
public IMessage send(Object message, long timeout) throws InterruptedException { List<WriteFuture> futures = new ArrayList<>(); Set<String> errorSending = new HashSet<>(); for (IoSession session : server.sessions.keySet()) { futures.add(session.write(message)); } long waitUntil = System.currentTimeMillis() + timeout; for (WriteFuture future : futures) { future.await(waitUntil - System.currentTimeMillis()); if (!future.isDone() || !future.isWritten()) { errorSending.add(future.getSession().toString()); } } if (!errorSending.isEmpty()) { throw new SendMessageFailedException(String.format("Message wasn't send during %d milliseconds. %s", timeout, String.join(System.lineSeparator(), errorSending))); } return message instanceof IMessage ? (IMessage) message : null; }
Example #9
Source File: MINASession.java From sailfish-core with Apache License 2.0 | 6 votes |
public IMessage send(Object message, long timeout) throws InterruptedException { if(!isConnected()) { throw new SendMessageFailedException("Session is not connected: " + this); } WriteFuture future = session.write(prepareMessage(message)); if(future.await(timeout)) { if(!future.isDone()) { throw new SendMessageFailedException("Send operation is not done. Session: " + this, future.getException()); } if(!future.isWritten()) { throw new SendMessageFailedException("Write operation is not done. Session: " + this, future.getException()); } } else { throw new SendMessageFailedException("Send operation is not completed. Session: " + this, future.getException()); } if(future.getException() != null) { throw new SendMessageFailedException("Message send failed. Session: " + this, future.getException()); } return message instanceof IMessage ? (IMessage)message : null; }
Example #10
Source File: SimpleClient.java From gameserver with Apache License 2.0 | 5 votes |
@Override public WriteFuture sendMessageToServer(Object msg) { try { if ( isResourceProtected ) { resourceLock.lock(); } if ( session == null || !session.isConnected() ) { if ( logger.isDebugEnabled() ) { logger.debug("Client #{} try to reconnect. session:{}, isConnected:", this.clientNo, session); } connectToServer(); } if ( session == null || !session.isConnected() ) { return null; } WriteFuture future = session.write(msg); if ( this.statListener != null ) { future.addListener(statListener); } if ( logger.isDebugEnabled() ) { logger.debug("Client send message to server."); } return future; } catch (Throwable t) { if ( logger.isDebugEnabled() ) { logger.debug(t.getMessage(), t); } } finally { if ( isResourceProtected ) { resourceLock.unlock(); } } return null; }
Example #11
Source File: DefaultWriteRequest.java From jane with GNU Lesser General Public License v3.0 | 5 votes |
/** * @param message a message to write * @param future a future that needs to be notified when an operation is finished */ public DefaultWriteRequest(Object message, WriteFuture future) { if (message == null) throw new IllegalArgumentException("message"); this.message = message; this.future = (future != null ? future : UNUSED_FUTURE); }
Example #12
Source File: SslFilter.java From neoscada with Eclipse Public License 1.0 | 5 votes |
/** * Stops the SSL session by sending TLS <tt>close_notify</tt> message to * initiate TLS closure. * * @param session the {@link IoSession} to initiate TLS closure * @throws SSLException if failed to initiate TLS closure * @throws IllegalArgumentException if this filter is not managing the specified session */ public WriteFuture stopSsl(IoSession session) throws SSLException { SslHandler handler = getSslSessionHandler(session); NextFilter nextFilter = (NextFilter) session.getAttribute(NEXT_FILTER); WriteFuture future; synchronized (handler) { future = initiateClosure(nextFilter, session); } handler.flushScheduledEvents(); return future; }
Example #13
Source File: AbstractProxyLogicHandler.java From neoscada with Eclipse Public License 1.0 | 5 votes |
/** * Writes data to the proxy server. * * @param nextFilter the next filter * @param data Data buffer to be written. */ protected WriteFuture writeData(final NextFilter nextFilter, final IoBuffer data) { // write net data ProxyHandshakeIoBuffer writeBuffer = new ProxyHandshakeIoBuffer(data); LOGGER.debug(" session write: {}", writeBuffer); WriteFuture writeFuture = new DefaultWriteFuture(getSession()); getProxyFilter().writeData(nextFilter, getSession(), new DefaultWriteRequest(writeBuffer, writeFuture), true); return writeFuture; }
Example #14
Source File: SslHandler.java From jane with GNU Lesser General Public License v3.0 | 5 votes |
WriteFuture writeNetBuffer(NextFilter nextFilter, boolean needFuture) throws Exception { // Check if any net data needed to be writen if (outNetBuffer == null || !outNetBuffer.hasRemaining()) return null; // no; bail out // set flag that we are writing encrypted data (used in SSLFilter.filterWrite()) writingEncryptedData = true; // write net data WriteFuture writeFuture = (needFuture ? new DefaultWriteFuture(session) : null); try { IoBuffer writeBuffer = fetchOutNetBuffer(); sslFilter.filterWrite(nextFilter, session, writeFuture != null ? new DefaultWriteRequest(writeBuffer, writeFuture) : writeBuffer); // loop while more writes required to complete handshake while (handshakeStatus == HandshakeStatus.NEED_WRAP && !isInboundDone()) { try { handshake(nextFilter); } catch (SSLException ssle) { SSLException newSsle = new SSLHandshakeException("SSL handshake failed"); newSsle.initCause(ssle); throw newSsle; } IoBuffer currentOutNetBuffer = fetchOutNetBuffer(); if (currentOutNetBuffer != null && currentOutNetBuffer.hasRemaining()) { writeFuture = (needFuture ? new DefaultWriteFuture(session) : null); sslFilter.filterWrite(nextFilter, session, writeFuture != null ? new DefaultWriteRequest(currentOutNetBuffer, writeFuture) : currentOutNetBuffer); } } } finally { writingEncryptedData = false; } return writeFuture; }
Example #15
Source File: TestReloadClassLoader.java From gameserver with Apache License 2.0 | 5 votes |
@Test public void testClassLoaderLeak2() throws Exception { int max = 10000; File sourceFile = new File(reloadSourceDir); URL[] urls = new URL[]{sourceFile.toURL()}; // ReloadProtocolCodecFilter filter = ReloadProtocolCodecFilter.getInstance( // GameServer.PROTOCOL_CODEC, GameServer.PROTOCOL_HANDLER, urls); SocketConnector connector = new NioSocketConnector(); // connector.getFilterChain().addLast("codec", filter); connector.setHandler(new ClientHandler()); //Send 1000 connections. try { for ( int i=0; i<Integer.MAX_VALUE; i++ ) { ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 3443)); future.awaitUninterruptibly(); IoSession session = future.getSession(); IoBuffer buffer = IoBuffer.allocate(8); buffer.putShort((short)8); buffer.putShort((short)0); buffer.putInt(i); WriteFuture wfuture = session.write(buffer); wfuture.awaitUninterruptibly(); } } catch (Exception e) { e.printStackTrace(); fail(); } }
Example #16
Source File: SslFilter.java From jane with GNU Lesser General Public License v3.0 | 5 votes |
private WriteFuture initiateClosure(NextFilter nextFilter, IoSession session, boolean needFuture) throws Exception { SslHandler sslHandler = getSslSessionHandler(session); WriteFuture future; // if already shutdown try { synchronized (sslHandler) { if (!sslHandler.closeOutbound()) return DefaultWriteFuture.newNotWrittenFuture(session, new IllegalStateException("SSL session is shutdown already")); // there might be data to write out here? future = sslHandler.writeNetBuffer(nextFilter, needFuture); if (needFuture && future == null) future = DefaultWriteFuture.newWrittenFuture(session); if (sslHandler.isInboundDone()) sslHandler.destroy(); } if (session.containsAttribute(USE_NOTIFICATION)) sslHandler.scheduleMessageReceived(nextFilter, SESSION_UNSECURED); } catch (SSLException se) { sslHandler.release(); throw se; } return future; }
Example #17
Source File: MockProtocolEncoderOutput.java From sailfish-core with Apache License 2.0 | 5 votes |
@Override public WriteFuture flush() { DummySession dummySession = new DummySession(); DefaultWriteFuture writeFuture = new DefaultWriteFuture(dummySession); return writeFuture; }
Example #18
Source File: MessageUtil.java From CXTouch with GNU General Public License v3.0 | 5 votes |
public static void sendMessage(IoSession session, Message message) throws MessageException { if (session == null || !session.isConnected()) { throw new MessageException("Connection is invalid!"); } IoBuffer buffer = message.getBinary(); buffer.flip(); int size = buffer.remaining(); WriteFuture future = session.write(buffer); }
Example #19
Source File: SslFilter.java From jane with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void filterClose(final NextFilter nextFilter, final IoSession session) throws Exception { SslHandler sslHandler = (SslHandler)session.getAttribute(SSL_HANDLER); if (sslHandler == null) { // The connection might already have closed, or SSL might have not started yet. nextFilter.filterClose(); return; } WriteFuture future = null; try { synchronized (sslHandler) { if (isSslStarted(session)) { future = initiateClosure(nextFilter, session, true); future.addListener(__ -> nextFilter.filterClose()); } } sslHandler.flushScheduledEvents(); } catch (SSLException se) { sslHandler.release(); throw se; } finally { if (future == null) nextFilter.filterClose(); } }
Example #20
Source File: ClientPool.java From gameserver with Apache License 2.0 | 5 votes |
@Override public WriteFuture sendMessageToServer(Object msg) { Client client = null; try { client = clientQueue.take(); WriteFuture future = client.sendMessageToServer(msg); return future; } catch (InterruptedException e) { } finally { clientQueue.offer(client); } return null; }
Example #21
Source File: Client.java From gameserver with Apache License 2.0 | 5 votes |
/** * Send a message to server. * @param msg */ private void sendRequest(MessageLite msg) { requestCount.incrementAndGet(); XinqiMessage request = new XinqiMessage(); request.index = 0; request.payload = msg; request.type = MessageToId.messageToId(msg); WriteFuture future = session.write(request); future.awaitUninterruptibly(); if ( !future.isWritten() ) { future.getException().printStackTrace(); fail("testBceLogin failed"); } }
Example #22
Source File: RpcLocker.java From sumk with Apache License 2.0 | 5 votes |
@Override public void operationComplete(final WriteFuture future) { if (future.getException() == null) { return; } SoaExcutors.getClientThreadPool().execute(() -> { if (LockHolder.remove(req.getSn()) == null) { return; } if (url != null) { HostChecker.get().addDownUrl(url); } wakeup(RpcResult.sendFailed(req, future.getException())); }); }
Example #23
Source File: BceLoginHandlerTest.java From gameserver with Apache License 2.0 | 5 votes |
@Test public void testSessionNotFoundUser() throws Exception { String userName = randomUserName(); BceLogin.Builder payload = BceLogin.getDefaultInstance().newBuilderForType(); payload.setUsername(userName); payload.setPassword("000000"); BceLogin msg = payload.build(); XinqiMessage message = new XinqiMessage(); message.index = 1; message.type = MessageToId.messageToId(msg); message.payload = msg; BceLoginHandler handler = BceLoginHandler.getInstance(); IoSession session = createMock(IoSession.class); expect(session.write(anyObject())).andAnswer(new IAnswer<WriteFuture>(){ @Override public WriteFuture answer() throws Throwable { XinqiMessage response = (XinqiMessage)getCurrentArguments()[0]; BseLogin login = (BseLogin)response.payload; assertEquals(ErrorCode.NOTFOUND.ordinal(), login.getCode()); return null; } }).times(1); replay(session); handler.messageProcess(session, message, null); verify(session); }
Example #24
Source File: WebSocketConnection.java From red5-websocket with Apache License 2.0 | 5 votes |
/** * Sends the handshake response. * * @param wsResponse */ public void sendHandshakeResponse(HandshakeResponse wsResponse) { log.debug("Writing handshake on session: {}", session.getId()); // create write future handshakeWriteFuture = session.write(wsResponse); handshakeWriteFuture.addListener(new IoFutureListener<WriteFuture>() { @Override public void operationComplete(WriteFuture future) { IoSession sess = future.getSession(); if (future.isWritten()) { // handshake is finished log.debug("Handshake write success! {}", sess.getId()); // set completed flag sess.setAttribute(Constants.HANDSHAKE_COMPLETE); // set connected state on ws connection if (connected.compareAndSet(false, true)) { try { // send queued packets queue.forEach(entry -> { sess.write(entry); queue.remove(entry); }); } catch (Exception e) { log.warn("Exception draining queued packets on session: {}", sess.getId(), e); } } } else { log.warn("Handshake write failed from: {} to: {}", sess.getLocalAddress(), sess.getRemoteAddress()); } } }); }
Example #25
Source File: MessageClientTest.java From gameserver with Apache License 2.0 | 5 votes |
/** * Deprecated test case since the client pool is used. * @throws Exception */ public void testConnectTimeoutToServer() throws Exception { server.stopServer(); MessageClient client = new MessageClient(host, port); assertTrue(!client.connectToServer()); SessionRawMessage msg = createSessionMessage(); server.startServer(host, port); WriteFuture future = client.sendMessageToServer(msg); future.await(); assertNotNull(future); }
Example #26
Source File: StatClient.java From gameserver with Apache License 2.0 | 5 votes |
/** * Send a message to server. * * @param msg */ public final WriteFuture sendDataToStatServer(Account account, String uuid, StatAction action, Object... params) { if ( statEnabled ) { try { CStatAction.Builder builder = CStatAction.newBuilder(); builder.setAction(action.toString()); builder.setTimestamp(System.currentTimeMillis()); if ( account != null ) { if ( account.getUserName() != null ) { builder.setRolename(account.getUserName()); } } builder.setUuid(uuid); if ( params != null && params.length > 0 ) { for ( Object param : params ) { if ( param != null ) { String p = param.toString(); if ( p.length()>30 ) { p = p.substring(0, 30); } builder.addParams(p); } else { builder.addParams(Constant.EMPTY); } } } XinqiMessage message = new XinqiMessage(); message.payload = builder.build(); message.type = MessageToId.messageToId(message.payload); boolean success = messageQueue.offer(message); } catch (Exception e) { logger.debug("#sendDataToStatServer: fail {}", e.getMessage()); } } return null; }
Example #27
Source File: StatClient.java From gameserver with Apache License 2.0 | 5 votes |
/** * Send a message to server. * * @param msg */ public final WriteFuture sendDataToStatServer(BasicUser user, String uuid, StatAction action, Object... params) { if ( statEnabled ) { try { CStatAction.Builder builder = CStatAction.newBuilder(); builder.setAction(action.toString()); builder.setTimestamp(System.currentTimeMillis()); if ( user != null ) { if ( user.getRoleName() != null ) { builder.setRolename(user.getRoleName()); } } builder.setUuid(uuid); if ( params != null && params.length > 0 ) { for ( Object param : params ) { if ( param != null ) { String p = param.toString(); if ( p.length()>30 ) { p = p.substring(0, 30); } builder.addParams(p); } else { builder.addParams(Constant.EMPTY); } } } XinqiMessage message = new XinqiMessage(); message.payload = builder.build(); message.type = MessageToId.messageToId(message.payload); boolean success = messageQueue.offer(message); } catch (Exception e) { logger.debug("#sendDataToStatServer: fail {}", e.getMessage()); } } return null; }
Example #28
Source File: StatClient.java From gameserver with Apache License 2.0 | 5 votes |
/** * Send * @param user * @param action * @param params * @return */ public final WriteFuture sendDataToStatServer(BasicUser user, StatAction action, Object... params) { String uuid = Constant.EMPTY; if ( user != null && user.getUuid() != null ) { uuid = user.getUuid(); } return sendDataToStatServer(user, uuid, action, params); }
Example #29
Source File: GameSession.java From GameServer with Apache License 2.0 | 5 votes |
/** * 发送消息给客户端 * @param msg * @return */ public WriteFuture sendMsg(ResponseMsg msg) { if (session == null || !session.isConnected() || session.isClosing()) { return null; } return session.write(msg); }
Example #30
Source File: DefaultWriteRequest.java From neoscada with Eclipse Public License 1.0 | 5 votes |
/** * Creates a new instance. * * @param message a message to write * @param future a future that needs to be notified when an operation is finished * @param destination the destination of the message. This property will be * ignored unless the transport supports it. */ public DefaultWriteRequest(Object message, WriteFuture future, SocketAddress destination) { if (message == null) { throw new IllegalArgumentException("message"); } if (future == null) { future = UNUSED_FUTURE; } this.message = message; this.future = future; this.destination = destination; }