/** {@inheritDoc} */ @Override public void messageReceived(IoSession session, Object message) throws Exception { if (log.isTraceEnabled()) { log.trace("messageReceived session: {} message: {}", session, message); log.trace("Filter chain: {}", session.getFilterChain()); } String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID); if (log.isTraceEnabled()) { log.trace("Message received on session: {} id: {}", session.getId(), sessionId); } RTMPMinaConnection conn = (RTMPMinaConnection) RTMPConnManager.getInstance().getConnectionBySessionId(sessionId); if (conn != null) { if (message != null) { if (message instanceof Packet) { byte state = conn.getStateCode(); // checking the state before allowing a task to be created will hopefully prevent rejected // task exceptions if (state != RTMP.STATE_DISCONNECTING && state != RTMP.STATE_DISCONNECTED) { conn.handleMessageReceived((Packet) message); } else { log.info( "Ignoring received message on {} due to state: {}", sessionId, RTMP.states[state]); } } } } else { log.warn("Connection was not found for {}, force closing", sessionId); forceClose(session); } }
@Override public void encode(IoSession session, Object o, ProtocolEncoderOutput out) throws Exception { PacketBuilder message = (PacketBuilder) o; // Allocate a buffer of the exact size for the packet IoBuffer buffer = IoBuffer.allocate(Packet.HEADER_SIZE + message.size(), false); // Write the packet header int ordinal = message.getType().ordinal(); // If encryption is enabled, encrypt the packet type if (session.containsAttribute("encrypter")) { ISAACAlgorithm encrypter = (ISAACAlgorithm) session.getAttribute("encrypter"); ordinal += encrypter.nextInt(); } // Write the packet headers buffer.putInt(ordinal); buffer.putInt(message.size()); // Write the packet payload buffer.put(message.getPayload()); // Flip then output out.write(buffer.flip()); }
@Test public void testWriteWhileWriteInProgress() throws Exception { AbstractStreamWriteFilter<M> filter = createFilter(); M message = createMessage(new byte[5]); Queue<WriteRequest> queue = new LinkedList<WriteRequest>(); /* * Make up the situation. */ session.setAttribute(filter.CURRENT_STREAM, message); session.setAttribute(filter.WRITE_REQUEST_QUEUE, queue); NextFilter nextFilter = EasyMock.createMock(NextFilter.class); /* * Replay. (We recorded *nothing* because nothing should occur.) */ EasyMock.replay(nextFilter); WriteRequest wr = new DefaultWriteRequest(new Object(), new DummyWriteFuture()); filter.filterWrite(nextFilter, session, wr); assertEquals(1, queue.size()); assertSame(wr, queue.poll()); /* * Verify. */ EasyMock.verify(nextFilter); session.removeAttribute(filter.CURRENT_STREAM); session.removeAttribute(filter.WRITE_REQUEST_QUEUE); }
public void sessionOpened(IoSession session) throws Exception { if (info != null) { session.write(info); } else if (queryContext != null && !queryContext.equals("")) { session.write(queryContext); } }
public void exceptionCaught(IoSession session, Throwable cause) throws Exception { System.out.println(cause.getMessage()); CmdListener cmdListener = (CmdListener) session.getAttribute("CmdListener"); cmdListener.setClose(); session.close(true); cmdListener.onException(cause); }
/** Calls {@link IoServiceListener#sessionDestroyed(IoSession)} for all registered listeners. */ public void fireSessionDestroyed(IoSession session) { // Try to remove the remaining empty session set after removal. if (managedSessions.remove(Long.valueOf(session.getId())) == null) { return; } // Fire session events. session.getFilterChain().fireSessionClosed(); // Fire listener events. try { for (IoServiceListener l : listeners) { try { l.sessionDestroyed(session); } catch (Throwable e) { ExceptionMonitor.getInstance().exceptionCaught(e); } } } finally { // Fire a virtual service deactivation event for the last session of the connector. if (session.getService() instanceof IoConnector) { boolean lastSession = false; synchronized (managedSessions) { lastSession = managedSessions.isEmpty(); } if (lastSession) { fireServiceDeactivated(); } } } }
@Override public boolean send(String data) { // Check for and disconnect slow consumers. if (maxScheduledWriteRequests > 0 && ioSession.getScheduledWriteMessages() >= maxScheduledWriteRequests) { Session qfjSession = (Session) ioSession.getAttribute(SessionConnector.QF_SESSION); try { qfjSession.disconnect("Slow consumer", true); } catch (IOException e) { } return false; } // The data is written asynchronously in a MINA thread WriteFuture future = ioSession.write(data); if (synchronousWrites) { try { if (!future.awaitUninterruptibly(synchronousWriteTimeout)) { log.error("Synchronous write timed out after " + synchronousWriteTimeout + "ms"); return false; } } catch (RuntimeException e) { log.error("Synchronous write failed: " + e.getMessage()); return false; } } return true; }
private void disconnectSessions() { if (!(service instanceof IoAcceptor)) { return; } if (!((IoAcceptor) service).isCloseOnDeactivation()) { return; } Object lock = new Object(); IoFutureListener<IoFuture> listener = new LockNotifyingListener(lock); for (IoSession s : managedSessions.values()) { s.close().addListener(listener); } try { synchronized (lock) { while (!managedSessions.isEmpty()) { lock.wait(500); } } } catch (InterruptedException ie) { // Ignored } }
/* * (non-Javadoc) * * @see * org.apache.mina.core.service.IoHandlerAdapter#sessionClosed(org.apache * .mina.core.session.IoSession) */ public void sessionClosed(IoSession session) throws Exception { log.debug("closed stub: " + session.getRemoteAddress()); TConn d = (TConn) session.getAttribute("conn"); if (d != null) { d.close(); } }
@Override public void exceptionCaught(IoSession session, Throwable cause) { cause.printStackTrace(); // (7) System.out.println("[Server] Client:" + session.getRemoteAddress() + "异常"); // 遇到未捕获的异常,则关闭连接 session.close(true); }
protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { DecoderState decoderState = (DecoderState) session.getAttribute(DECODER_STATE_KEY); if (decoderState == null) { decoderState = new DecoderState(); session.setAttribute(DECODER_STATE_KEY, decoderState); } if (decoderState.image1 == null) { // try to read first image if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) { decoderState.image1 = readImage(in); } else { // not enough data available to read first image return false; } } if (decoderState.image1 != null) { // try to read second image if (in.prefixedDataAvailable(4, MAX_IMAGE_SIZE)) { BufferedImage image2 = readImage(in); ImageResponse imageResponse = new ImageResponse(decoderState.image1, image2); out.write(imageResponse); decoderState.image1 = null; return true; } else { // not enough data available to read second image return false; } } return false; }
/** Disconnects from the world model. */ protected void _disconnect() { IoSession currentSession = this.session; this.session = null; this.sentHandshake = null; this.receivedHandshake = null; this.attributeAliasValues.clear(); this.originAliasValues.clear(); if (currentSession != null && !currentSession.isClosing()) { log.info( "Closing connection to World Model (client) at {} (waiting {}ms).", currentSession.getRemoteAddress(), Long.valueOf(this.connectionTimeout)); while (!currentSession.close(false).awaitUninterruptibly(this.connectionTimeout)) { log.error("Connection didn't close after {}ms.", Long.valueOf(this.connectionTimeout)); } } if (currentSession != null) { for (ConnectionListener listener : this.connectionListeners) { listener.connectionInterrupted(this); } } }
/** Invoked when a message is received. */ public void messageReceived(IoSession session, Object message) throws Exception { log.debug("messageReceived()..."); // <iq id="567-3" type="result"><test>aaaa</test></iq> // <iq id="567-3" type="result"><test>aaaa</test></iq> // log.info("RCVD: " + message); // Get the stanza handler StanzaHandler handler = (StanzaHandler) session.getAttribute(STANZA_HANDLER); // Get the XMPP packet parser int hashCode = Thread.currentThread().hashCode(); XMPPPacketReader parser = parsers.get(hashCode); if (parser == null) { parser = new XMPPPacketReader(); parser.setXPPFactory(factory); parsers.put(hashCode, parser); } // The stanza handler processes the message try { handler.process((String) message, parser); } catch (Exception e) { log.error("Closing connection due to error while processing message: " + message, e); Connection connection = (Connection) session.getAttribute(CONNECTION); connection.close(); } }
/** * Connect by tcp. * * @param host the host * @param port the port * @return the t conn */ public static synchronized TConn connectByTcp(String host, int port, long timeout) { TimeStamp t = TimeStamp.create(); try { if (tcpconnector == null) { tcpconnector = new TDCConnector(); } tcpconnector.connector.setConnectTimeoutMillis(timeout); ConnectFuture connFuture = tcpconnector.connector.connect(new InetSocketAddress(host, port)); connFuture.awaitUninterruptibly(timeout); IoSession session = connFuture.getSession(); TConn c = new TConn(session); session.setAttribute("conn", c); return c; } catch (Exception e) { log.error( "error, [" + host + ":" + port + "], cost: " + t.past() + "ms, timeout=" + timeout, e); } return null; }
private void keepAliveFilterForIdleStatus(IdleStatus status) throws Exception { NioSocketConnector connector = new NioSocketConnector(); KeepAliveFilter filter = new KeepAliveFilter(new ClientFactory(), status, EXCEPTION, INTERVAL, TIMEOUT); filter.setForwardEvent(true); connector.getFilterChain().addLast("keep-alive", filter); final AtomicBoolean gotException = new AtomicBoolean(false); connector.setHandler( new IoHandlerAdapter() { @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { // cause.printStackTrace(); gotException.set(true); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { // Do nothing } }); ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", port)).awaitUninterruptibly(); IoSession session = future.getSession(); assertNotNull(session); Thread.sleep((INTERVAL + TIMEOUT + 1) * 1000); assertFalse("got an exception on the client", gotException.get()); session.close(true); connector.dispose(); }
private IoSession newSessionWithoutLock(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { DatagramChannel handle = boundHandles.get(localAddress); if (handle == null) { throw new IllegalArgumentException("Unknown local address: " + localAddress); } IoSession session; synchronized (sessionRecycler) { session = sessionRecycler.recycle(remoteAddress); if (session != null) { return session; } // If a new session needs to be created. NioSession newSession = newSession(this, handle, remoteAddress); getSessionRecycler().put(newSession); session = newSession; } initSession(session, null, null); try { this.getFilterChainBuilder().buildFilterChain(session.getFilterChain()); getListeners().fireSessionCreated(session); } catch (Exception e) { ExceptionMonitor.getInstance().exceptionCaught(e); } return session; }
@Override public void messageReceived(IoSession session, Object message) { // client only sends AddMessage. otherwise, we will have to identify // its type using instanceof operator. AddMessage am = (AddMessage) message; // add the value to the current sum. int sum = ((Integer) session.getAttribute(SUM_KEY)).intValue(); int value = am.getValue(); long expectedSum = (long) sum + value; if (expectedSum > Integer.MAX_VALUE || expectedSum < Integer.MIN_VALUE) { // if the sum overflows or underflows, return error message ResultMessage rm = new ResultMessage(); rm.setSequence(am.getSequence()); // copy sequence rm.setOk(false); session.write(rm); } else { // sum up sum = (int) expectedSum; session.setAttribute(SUM_KEY, new Integer(sum)); // return the result message ResultMessage rm = new ResultMessage(); rm.setSequence(am.getSequence()); // copy sequence rm.setOk(true); rm.setValue(sum); session.write(rm); } }
@Override public void fire() { IoSession session = getSession(); NextFilter nextFilter = getNextFilter(); IoEventType type = getType(); if (DEBUG) { LOGGER.debug("Firing a {} event for session {}", type, session.getId()); } switch (type) { case MESSAGE_RECEIVED: Object parameter = getParameter(); nextFilter.messageReceived(session, parameter); break; case MESSAGE_SENT: WriteRequest writeRequest = (WriteRequest) getParameter(); nextFilter.messageSent(session, writeRequest); break; case WRITE: writeRequest = (WriteRequest) getParameter(); nextFilter.filterWrite(session, writeRequest); break; case CLOSE: nextFilter.filterClose(session); break; case EXCEPTION_CAUGHT: Throwable throwable = (Throwable) getParameter(); nextFilter.exceptionCaught(session, throwable); break; case SESSION_IDLE: nextFilter.sessionIdle(session, (IdleStatus) getParameter()); break; case SESSION_OPENED: nextFilter.sessionOpened(session); break; case SESSION_CREATED: nextFilter.sessionCreated(session); break; case SESSION_CLOSED: nextFilter.sessionClosed(session); break; default: throw new IllegalArgumentException("Unknown event type: " + type); } if (DEBUG) { LOGGER.debug("Event {} has been fired for session {}", type, session.getId()); } }
@Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { Object userSid = session.getAttribute(BaseHandler.ATTR_USER_SID); if (userSid != null) { logger.debug("===> sessionIdle:" + userSid.toString()); } session.closeOnFlush(); }
///////////////////////////////////// // 结合CumulativeProtocolDecoder///////////////////////////////////////////////// // 获取session的context public Context getContext(IoSession session) { Context ctx = (Context) session.getAttribute(CONTEXT); if (ctx == null) { ctx = new Context(); session.setAttribute(CONTEXT, ctx); } return ctx; }
public Exchange createExchange(IoSession session, Object payload) { Exchange exchange = createExchange(); exchange.getIn().setHeader(Mina2Constants.MINA_IOSESSION, session); exchange.getIn().setHeader(Mina2Constants.MINA_LOCAL_ADDRESS, session.getLocalAddress()); exchange.getIn().setHeader(Mina2Constants.MINA_REMOTE_ADDRESS, session.getRemoteAddress()); Mina2PayloadHelper.setIn(exchange, payload); return exchange; }
/* * (non-Javadoc) * * @see * org.apache.mina.core.service.IoHandlerAdapter#sessionIdle(org.apache. * mina.core.session.IoSession, org.apache.mina.core.session.IdleStatus) */ public void sessionIdle(IoSession session, IdleStatus status) throws Exception { if (IdleStatus.BOTH_IDLE.equals(status)) { Long l = (Long) session.getAttribute("last"); if (l != null && System.currentTimeMillis() - l > 60 * 1000) { session.close(true); } } }
@Override public void onPreRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException { IoSession session = parent.getSession(); stopSsl(session); session.removeAttribute(NEXT_FILTER); session.removeAttribute(SSL_HANDLER); }
@Override public void sessionOpened(IoSession session) { // set idle time to 60 seconds session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60); // initial sum is zero session.setAttribute(SUM_KEY, new Integer(0)); }
/** * Handles a packet. * * @param session The session. * @param packet The packet. */ public void handle(IoSession session, Packet packet) { try { packetHandlers[packet.getOpcode()].handle((Player) session.getAttribute("player"), packet); } catch (final Exception ex) { logger.log(Level.SEVERE, "Exception handling packet.", ex); session.close(false); } }
public void exceptionCaught(IoSession session, Throwable throwable) throws Exception { if (throwable instanceof ISOException && ignoreISOExceptions) { return; } getLog().error(getName() + ".session" + session.getRemoteAddress(), throwable); session.close(true); }
@Override public void messageReceived(Object in, IoSession session) throws Exception { RTMPConnection conn = (RTMPConnection) session.getAttribute(RTMPConnection.RTMP_CONNECTION_KEY); RTMP state = (RTMP) session.getAttribute(ProtocolState.SESSION_KEY); IRTMPEvent message = null; final Packet packet = (Packet) in; message = packet.getMessage(); final Header header = packet.getHeader(); final Channel channel = conn.getChannel(header.getChannelId()); // Increase number of received messages conn.messageReceived(); if (header.getDataType() == TYPE_BYTES_READ) { // TODO need to sync the bytes read on edge and origin onStreamBytesRead(conn, channel, header, (BytesRead) message); } if (header.getDataType() == TYPE_INVOKE) { final IServiceCall call = ((Invoke) message).getCall(); final String action = call.getServiceMethodName(); if (call.getServiceName() == null && !conn.isConnected() && StreamAction.valueOf(action).equals(StreamAction.CONNECT)) { handleConnect(conn, channel, header, (Invoke) message, (RTMP) state); return; } } switch (header.getDataType()) { case TYPE_CHUNK_SIZE: case TYPE_INVOKE: case TYPE_FLEX_MESSAGE: case TYPE_NOTIFY: case TYPE_AUDIO_DATA: case TYPE_VIDEO_DATA: case TYPE_FLEX_SHARED_OBJECT: case TYPE_FLEX_STREAM_SEND: case TYPE_SHARED_OBJECT: case TYPE_BYTES_READ: forwardPacket(conn, packet); break; case TYPE_PING: onPing(conn, channel, header, (Ping) message); break; default: if (log.isDebugEnabled()) { log.debug("Unknown type: {}", header.getDataType()); } } if (message instanceof Unknown) { log.info(message.toString()); } if (message != null) { message.release(); } }
private void closeSession(IoSession session) { String room = (String) session.getAttribute(ROOM, null); if (room != null) { log.info("Closing session [" + room + "]. "); } else { log.info("Cannot determine session to close."); } CloseFuture future = session.close(true); }
/** Initialize the encoder and the decoder, storing them in the session attributes. */ private void initCodec(IoSession session) throws Exception { // Creates the decoder and stores it into the newly created session ProtocolDecoder decoder = factory.getDecoder(session); session.setAttribute(DECODER, decoder); // Creates the encoder and stores it into the newly created session ProtocolEncoder encoder = factory.getEncoder(session); session.setAttribute(ENCODER, encoder); }
@Override public void messageReceived(NextFilter nextFilter, final IoSession session, Object message) throws Exception { int maxReadThroughput = this.maxReadThroughput; // process the request if our max is greater than zero if (maxReadThroughput > 0) { final State state = (State) session.getAttribute(STATE); long currentTime = System.currentTimeMillis(); long suspendTime = 0; boolean firstRead = false; synchronized (state) { state.readBytes += messageSizeEstimator.estimateSize(message); if (!state.suspendedRead) { if (state.readStartTime == 0) { firstRead = true; state.readStartTime = currentTime - 1000; } long throughput = (state.readBytes * 1000 / (currentTime - state.readStartTime)); if (throughput >= maxReadThroughput) { suspendTime = Math.max( 0, state.readBytes * 1000 / maxReadThroughput - (firstRead ? 0 : currentTime - state.readStartTime)); state.readBytes = 0; state.readStartTime = 0; state.suspendedRead = suspendTime != 0; adjustReadBufferSize(session); } } } if (suspendTime != 0) { session.suspendRead(); scheduledExecutor.schedule( new Runnable() { public void run() { synchronized (state) { state.suspendedRead = false; } session.resumeRead(); } }, suspendTime, TimeUnit.MILLISECONDS); } } nextFilter.messageReceived(session, message); }