/* * (non-Javadoc) * * @see * org.apache.mina.core.service.IoHandlerAdapter#sessionCreated(org.apache * .mina.core.session.IoSession) */ public void sessionCreated(IoSession session) throws Exception { log.info("stub created:" + session.getRemoteAddress()); Counter.add("mdc", "connection", 1); TConn d = new TConn(session); d.set("x-forwarded-for", session.getRemoteAddress().toString()); session.setAttribute("conn", d); }
@Override public void messageReceived(IoSession session, Object msg) throws Exception { String xml = msg.toString(); System.out.println( "1. Message Recieved from : " + session.getRemoteAddress().toString() + "\nMessage " + xml); XPathHandler handler = new XPathHandler(); parser.parse(new ByteArrayInputStream(xml.getBytes()), handler); String xmlResponse = createResponse(handler.getXmlData()); System.out.println( "2. Message Response to : " + session.getRemoteAddress().toString() + "\nMessage " + xmlResponse); session.write(xmlResponse); }
@Override public void exceptionCaught(IoSession ioSession, Throwable cause) throws Exception { boolean disconnectNeeded = false; Session quickFixSession = findQFSession(ioSession); Throwable realCause = cause; if (cause instanceof ProtocolDecoderException && cause.getCause() != null) { realCause = cause.getCause(); } else { Throwable chain = cause; while (chain != null && chain.getCause() != null) { chain = chain.getCause(); if (chain instanceof IOException) { realCause = chain; break; } } } String reason; if (realCause instanceof IOException) { if (quickFixSession != null && quickFixSession.isEnabled()) { reason = "Socket exception (" + ioSession.getRemoteAddress() + "): " + cause; } else { reason = "Socket (" + ioSession.getRemoteAddress() + "): " + cause; } disconnectNeeded = true; } else if (realCause instanceof CriticalProtocolCodecException) { reason = "Critical protocol codec error: " + cause; disconnectNeeded = true; } else if (realCause instanceof ProtocolCodecException) { reason = "Protocol handler exception: " + cause; } else { reason = cause.toString(); } if (disconnectNeeded) { try { if (quickFixSession != null) { quickFixSession.disconnect(reason, true); } else { log.error(reason, cause); ioSession.closeNow(); } } finally { ioSession.setAttribute("QFJ_RESET_IO_CONNECTOR", Boolean.TRUE); } } else { log.error(reason, cause); } }
@Override public void exceptionCaught(IoSession session, Throwable cause) { cause.printStackTrace(); // (7) System.out.println("[Server] Client:" + session.getRemoteAddress() + "异常"); // 遇到未捕获的异常,则关闭连接 session.close(true); }
public void setIosession(IoSession iosession) { this.iosession = iosession; InetSocketAddress socket = (InetSocketAddress) iosession.getRemoteAddress(); this.setIp(socket.getAddress().getHostAddress()); this.setPort(socket.getPort()); iscon = true; }
/** 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); } } }
/* * (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(); } }
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; }
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 String getRemoteAddress() { final SocketAddress remoteAddress = ioSession.getRemoteAddress(); if (remoteAddress != null) { return remoteAddress.toString(); } return null; }
private String getLogSuffix(SessionID sessionID, IoSession protocolSession) { String suffix = ":"; if (sessionID != null) { suffix += "sessionID=" + sessionID.toString() + ";"; } if (protocolSession != null) { suffix += "address=" + protocolSession.getRemoteAddress(); } return suffix; }
/** Invoked when a connection has been opened. */ public void sessionOpened(IoSession session) throws Exception { log.debug("sessionOpened()..."); log.debug("remoteAddress=" + session.getRemoteAddress()); // Create a new XML parser XMLLightweightParser parser = new XMLLightweightParser("UTF-8"); session.setAttribute(XML_PARSER, parser); // Create a new connection Connection connection = new Connection(session); session.setAttribute(CONNECTION, connection); session.setAttribute(STANZA_HANDLER, new StanzaHandler(serverName, connection)); }
@Override public void connectionOpened(IoSession session) { if (this.session == null) { log.warn("Session was not correctly stored during connection set-up."); this.session = session; } log.info("Connected to World Model (client) at {}.", session.getRemoteAddress()); log.debug("Attempting to write handshake."); this.session.write(HandshakeMessage.getDefaultMessage()); }
/* * (non-Javadoc) * * @see * org.apache.mina.core.service.IoHandlerAdapter#sessionCreated(org.apache * .mina.core.session.IoSession) */ public void sessionCreated(IoSession session) throws Exception { String remote = session.getRemoteAddress().toString(); log.info("stub created:" + remote); /** check the allow ip */ if (TConn.ALLOW_IP == null || "*".equals(TConn.ALLOW_IP) || remote.matches(TConn.ALLOW_IP)) { TConn d = new TConn(session); session.setAttribute("conn", d); } else { log.warn("deny the connection:" + remote + ", allow ip:" + TConn.ALLOW_IP); session.close(true); } }
/** * 广播消息 * * @param message */ private void broadcast(String message, IoSession exceptSession) { // (8) synchronized (sessions) { for (IoSession session : sessions) { if (session.isConnected()) { if (session.equals(exceptSession)) { session.write("[You]" + message); } else { session.write("[Client" + session.getRemoteAddress() + "] " + message); } } } } }
private static String getSessionInfo(IoSession session) { if (session != null) { return "[" + (session.getAttribute("ID") == null ? String.valueOf(session.getId()) : session.getAttribute("ID")) + "]" + "[" + session.getId() + "] => " + session.getRemoteAddress(); } return "[NULL] => NULL"; }
private boolean isBlocked(IoSession session) { SocketAddress remoteAddress = session.getRemoteAddress(); if (remoteAddress instanceof InetSocketAddress) { InetAddress address = ((InetSocketAddress) remoteAddress).getAddress(); // check all subnets for (Subnet subnet : blacklist) { if (subnet.inSubnet(address)) { return true; } } } return false; }
@Override public void sessionIdle(IoSession session, IdleStatus status) { if (session == null) { return; } if (status.equals(IdleStatus.READER_IDLE)) { log.error("World Model timed-out. Disconnecting."); this._disconnect(); return; } if (status.equals(IdleStatus.WRITER_IDLE) || status.equals(IdleStatus.BOTH_IDLE)) { log.debug("Writing Keep-Alive message to World Model at {}", session.getRemoteAddress()); session.write(KeepAliveMessage.MESSAGE); } }
public boolean hasBannedIP() { boolean ret = false; try { Connection con = DatabaseConnection.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM ipbans WHERE ? LIKE CONCAT(ip, '%')"); ps.setString(1, session.getRemoteAddress().toString()); ResultSet rs = ps.executeQuery(); rs.next(); if (rs.getInt(1) > 0) { ret = true; } rs.close(); ps.close(); } catch (SQLException ex) { } return ret; }
@SuppressWarnings({"WhileLoopReplaceableByForEach"}) public void messageReceived(IoSession session, Object o) throws Exception { if (o instanceof NullMessage) { session.write(o); } else if (o instanceof ISOMsg) { getLog().info(getName() + ".session" + session.getRemoteAddress(), o); ISOMsg m = (ISOMsg) o; Iterator iter = requestListeners.iterator(); while (iter.hasNext()) { final SessionISOSource source = new SessionISOSource(session); m.setSource(source); m.setDirection(ISOMsg.INCOMING); if (((ISORequestListener) iter.next()).process(source, m)) { break; } } } }
@SuppressWarnings("rawtypes") public void run() { // pipeline if (message instanceof List) { List messages = (List) message; for (Object messageObject : messages) { threadPool.execute(new HandlerRunnable(session, messageObject, threadPool)); } } else { RequestWrapper request = (RequestWrapper) message; long beginTime = System.currentTimeMillis(); ResponseWrapper responseWrapper = ProtocolFactory.getServerHandler(request.getProtocolType()).handleRequest(request); final int id = request.getId(); // already timeout,so not return if ((System.currentTimeMillis() - beginTime) >= request.getTimeout()) { LOGGER.warn( "timeout,so give up send response to client,requestId is:" + id + ",client is:" + session.getRemoteAddress() + ",consumetime is:" + (System.currentTimeMillis() - beginTime) + ",timeout is:" + request.getTimeout()); return; } WriteFuture wf = session.write(responseWrapper); wf.addListener( new IoFutureListener() { public void operationComplete(IoFuture future) { if (!((WriteFuture) future).isWritten()) { LOGGER.error("server write response error,request id is: " + id); } } }); } }
@Override public void exceptionCaught(IoSession session, Throwable ex) throws Exception { System.out.println("Client error " + session.getRemoteAddress().toString()); ex.printStackTrace(); }
@Override public void sessionIdle(IoSession session, IdleStatus is1) throws Exception { System.out.println("Client iddle " + session.getRemoteAddress().toString()); }
@Override public void sessionClosed(IoSession session) throws Exception { System.out.println("Client say goodbye " + session.getRemoteAddress().toString()); }
@Override public void sessionOpened(IoSession session) throws Exception { System.out.println("Open session " + session.getRemoteAddress().toString()); }
@Override public void sessionCreated(IoSession session) throws Exception { System.out.println("Client connect " + session.getRemoteAddress().toString()); }
public void messageSent(IoSession session, Object o) throws Exception { if (o instanceof ISOMsg) { getLog().info(getName() + ".session" + session.getRemoteAddress(), o); } }
public void sessionClosed(IoSession session) throws Exception { connectedSessions--; getLog().info(getName() + ".session" + session.getRemoteAddress(), "session ended"); }
public void sessionOpened(IoSession session) throws Exception { connectedSessions++; getLog().info(getName() + ".session" + session.getRemoteAddress(), "session started"); }
/** * Service. * * @param o the o * @param session the session */ void service(IoBuffer o, IoSession session) { try { // System.out.println(o.remaining() + "/" + o.capacity()); session.setAttribute("last", System.currentTimeMillis()); SimpleIoBuffer in = (SimpleIoBuffer) session.getAttribute("buf"); if (in == null) { in = SimpleIoBuffer.create(4096); session.setAttribute("buf", in); } byte[] data = new byte[o.remaining()]; o.get(data); in.append(data); // log.debug("recv: " + data.length + ", " + // session.getRemoteAddress()); while (in.length() > 5) { in.mark(); /** * Byte 1: head of the package<br> * bit 7-6: "01", indicator of MDC<br> * bit 5: encrypt indicator, "0": no; "1": encrypted<br> * bit 4: zip indicator, "0": no, "1": ziped<br> * bit 0-3: reserved<br> * Byte 2-5: length of data<br> * Byte[…]: data array<br> */ byte head = in.read(); /** test the head indicator, if not correct close it */ if ((head & 0xC0) != 0x40) { log.info("flag is not correct! flag:" + head + ",from: " + session.getRemoteAddress()); session.close(true); return; } int len = in.getInt(); if (len <= 0 || len > MAX_SIZE) { log.error( "mdcconnector.Wrong lendth: " + len + "/" + MAX_SIZE + " - " + session.getRemoteAddress()); session.close(true); break; } if (in.length() < len) { in.reset(); break; } else { // do it // log.info("stub.package.size: " + len); byte[] b = new byte[len]; in.read(b); if (TConn.DEBUG) { log.debug("recv: " + Bean.toString(b)); } /** test the zip flag */ if ((head & 0x10) > 0) { b = Zip.unzip(b); } final TConn d = (TConn) session.getAttribute("conn"); if (d != null) { /** test the encrypted flag */ if ((head & 0x20) > 0) { b = DES.decode(b, d.deskey); } final byte[] bb = b; /** test if the packet is for mdc or app */ new WorkerTask() { @Override public void onExecute() { d.process(bb); } }.schedule(0); session.setAttribute("last", System.currentTimeMillis()); } } } } catch (Throwable e) { log.error("closing stub: " + session.getRemoteAddress(), e); session.close(true); } }