Ejemplo n.º 1
0
 public void sessionOpened(IoSession session) throws Exception {
   if (info != null) {
     session.write(info);
   } else if (queryContext != null && !queryContext.equals("")) {
     session.write(queryContext);
   }
 }
Ejemplo n.º 2
0
  @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);
    }
  }
 /**
  * 广播消息
  *
  * @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);
         }
       }
     }
   }
 }
  @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;
  }
Ejemplo n.º 5
0
 public static void sendMsg(IoSession session, String msg) {
   if (AESEncrypter.isDecryption) {
     msg = AESEncrypter.encrypt(msg);
   }
   log.info("mina-send:" + msg);
   session.write(msg);
 }
Ejemplo n.º 6
0
 @Override
 public void messageReceived(IoSession session, Object msg) throws Exception {
   if (msg instanceof String) {
     if (HEARTBEATREQUEST.equals(msg)) {
       session.write(HEARTBEATRESPONSE);
       lastTime = System.currentTimeMillis();
     } else {
       try {
         Object rs = handler.handle(msg);
         if (rs != null) session.write(rs);
       } catch (Exception e) {
         logger.error("handler处理异常", e);
       }
     }
   }
 }
Ejemplo n.º 7
0
  @Override
  public void messageReceived(IoSession session, Object message) {
    System.out.println("server received");

    try {
      if (message instanceof FileUploadRequest) {
        // FileUploadRequest 为传递过程中使用的DO。
        FileUploadRequest request = (FileUploadRequest) message;
        System.out.println(request.getFilename());
        if (out == null) {
          // 新建一个文件输入对象BufferedOutputStream,随便定义新文件的位置
          out = new BufferedOutputStream(new FileOutputStream("D:/log/" + request.getFilename()));
          out.write(request.getFileContent());
        } else {
          out.write(request.getFileContent());
        }
        count += request.getFileContent().length;

      } else if (message instanceof String) {
        if (((String) message).equals("finish")) {
          System.out.println("size is" + count);
          // 这里是进行文件传输后,要进行flush和close否则传递的文件不完整。
          out.flush();
          out.close();
          // 回执客户端信息,上传文件成功
          session.write("success");
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 8
0
  private void deliverRawText(String text, boolean asynchronous) {
    if (!isClosed()) {
      boolean errorDelivering = false;
      IoBuffer buffer = IoBuffer.allocate(text.length());
      buffer.setAutoExpand(true);
      try {
        // Charset charset = Charset.forName(CHARSET);
        // buffer.putString(text, charset.newEncoder());
        buffer.put(text.getBytes(CHARSET));
        if (flashClient) {
          buffer.put((byte) '\0');
        }
        buffer.flip();
        ioSessionLock.lock();
        try {
          if (asynchronous) {
            // OF-464: handle dropped connections (no backupDeliverer in this case?)
            if (!ioSession.isConnected()) {
              throw new IOException("Connection reset/closed by peer");
            }
            ioSession.write(buffer);
          } else {
            // Send stanza and wait for ACK (using a 2 seconds default timeout)
            boolean ok =
                ioSession
                    .write(buffer)
                    .awaitUninterruptibly(
                        JiveGlobals.getIntProperty("connection.ack.timeout", 2000));
            if (!ok) {
              Log.warn("No ACK was received when sending stanza to: " + this.toString());
            }
          }
        } finally {
          ioSessionLock.unlock();
        }
      } catch (Exception e) {
        Log.debug("Error delivering raw text:\n" + text, e);
        errorDelivering = true;
      }

      // Close the connection if delivering text fails and we are already not closing the connection
      if (errorDelivering && asynchronous) {
        close();
      }
    }
  }
Ejemplo n.º 9
0
 @Override
 public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
   super.sessionIdle(session, status);
   // 如果IoSession闲置,则关闭连接
   if (status == IdleStatus.BOTH_IDLE) {
     session.write(HEARTBEATRESPONSE);
   }
 }
Ejemplo n.º 10
0
  @Override
  public void messageReceived(IoSession session, Object message) throws Exception {
    logger.info("Received " + message);

    MyRequestObject myReqOjb = (MyRequestObject) message;
    MyResponseObject myResObj = new MyResponseObject(myReqOjb.getName(), myReqOjb.getValue());
    session.write(myResObj);
  }
Ejemplo n.º 11
0
 /** 这个方法在连接被打开时调用,它总是在sessionCreated()方法之后被调用。对于TCP 来 说,它是在连接被建立之后调用,你可以在这里执行一些认证操作、发送数据等。 */
 public void sessionOpened(IoSession session) throws Exception {
   LogUtil.print("sessionOpened");
   String clientId = SpfsUtil.getClientId();
   // 给mina发送clientId
   Log.e("msggg", clientId);
   if (null != clientId) {
     session.write("{\"clientId\":" + "\"" + clientId + "\"}");
   }
 }
Ejemplo n.º 12
0
  private int sendObject(BisonObject obj, IoSession session) {
    int ret = 0;
    try {
      int callType = obj.getCallType();
      if (callType == BeanCallCode.INTERFACE_CALL_ID) {
        byte[] data = ZipUtil.ZipObject(obj.getSendObject(), true);

        byte[] buf = new byte[8 + data.length];
        ByteUtil.writeInt(buf, 0, obj.getCallType());
        ByteUtil.writeInt(buf, 4, obj.getKey());
        System.arraycopy(data, 0, buf, 8, data.length);

        session.write(buf);
        data = (byte[]) null;
        buf = (byte[]) null;
        obj = null;
      } else {
        String methodName = obj.getMethodName();
        methodName = methodName == null ? "BeanCall" : methodName;

        byte[] data = ZipUtil.ZipObject(obj.getSendObject(), true);

        if (data == null) {
          this.logger.error(
              "please check send object is seriable! " + obj.getSendObject().getClass().getName());
        } else {
          byte[] buf = new byte[8 + data.length + methodName.length() + 1];
          ByteUtil.writeInt(buf, 0, obj.getCallType());
          ByteUtil.writeInt(buf, 4, obj.getKey());
          ByteUtil.writeString(buf, 8, methodName);
          System.arraycopy(data, 0, buf, 8 + methodName.length() + 1, data.length);
          session.write(buf);
          data = (byte[]) null;
          buf = (byte[]) null;
          obj = null;
        }
      }
    } catch (Exception e) {
      this.logger.error("sendObject", e);
      e.printStackTrace();
      ret = -5;
    }
    return ret;
  }
Ejemplo n.º 13
0
 /**
  * ***************************************
  * <li>描 述:发送消息<br>
  * <li>时 间:2013-9-26 下午5:19:06<br>
  * <li>参数: @param msgKey
  * <li>参数: @param message
  * <li>参数: @return<br>
  *     ***************************************
  */
 public boolean sendMessage(String message) {
   if (ioSession != null) {
     ioSession.write(message + " \r\n");
     logger.debug("已成功向MSG发送信息:" + message);
     return true;
   } else {
     logger.error("发送消息异常:MSG连接为空!");
     return false;
   }
 }
Ejemplo n.º 14
0
 @Override
 public void sessionOpened(IoSession session) throws Exception {
   StringBuffer loginStr = new StringBuffer();
   loginStr.append("LOGI ");
   loginStr.append(loginType).append(":").append(group).append(" ");
   loginStr.append(userName).append(":").append(groupId).append(" ");
   loginStr.append(password).append(" \r\n");
   session.write(loginStr.toString());
   logger.info("已向MSG发送登陆信息:" + loginStr.toString());
 }
 /** 发送注销消息 */
 public boolean sendLogoutMessage() {
   STEPParser app = ParserConfig.getInstance().getStep();
   Message message = StepMessage.getLogoutMessage(app);
   session.write(message);
   try {
     doLock();
   } catch (InterruptedException e) {
     log.error("Send Logout Message InterruptedException: ", e);
   }
   return false;
 }
Ejemplo n.º 16
0
  public void ping(long time) {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
      dout.writeLong(time);
      session.write(new NetMessage(1, bout.toByteArray()));
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * @Description: 发送消息到客户端
   *
   * @author whl
   * @date 2014-9-29 下午1:57:51
   */
  public void sendMessage(String[] keys, Object message) {
    for (String key : keys) {
      IoSession session = getSession(key);

      log.debug("反向发送消息到客户端Session---key=" + key + "----------消息=" + message);
      if (session == null) {
        return;
      }
      session.write(message);
    }
  }
Ejemplo n.º 18
0
 public boolean send(String message) {
   if (future.isConnected()) {
     // 等待连接创建完成
     future.awaitUninterruptibly();
     // 获取当前session
     session = future.getSession();
     session.write(message);
     return true;
   } else {
     return false;
   }
 }
 @Override
 public void execute(IoSession session) {
   MessageStatusChangeRequest request =
       ObjectJsonMapper.getObjectBy(getRequestAsString(), MessageStatusChangeRequest.class);
   messageDao.updateStatus(request.getMessageIdArray(), request.getStatus());
   messageStatusChangeHandler.handle(request);
   IoSession ses = SessionManager.getInstance().getSession(request.getTo());
   if (ses != null) {
     addResult(STATUS_CHANGED_KEY, request);
     ses.write(new ResponseBuilder(this).getResponse());
   }
 }
Ejemplo n.º 20
0
  /**
   * @Description: 发送消息到客户端
   *
   * @author whl
   * @date 2014-9-29 下午1:57:51
   */
  public void sendMessage(Integer[] keys, Object message) {
    for (Integer key : keys) {
      IoSession session = getSession(key);

      log.info("反向发送消息到客户端Session---key=" + key + "----------消息=" + message);
      if (session == null) {
        return;
      }
      JSONObject json = JSONObject.fromObject(message);
      session.write(json);
    }
  }
Ejemplo n.º 21
0
  public void sendSample() throws InterruptedException {
    IoSession session = rs232connector.getReceiverSession();
    // SendOnePacket(session, pkt, nc, 1000);
    CHYCAOutMessage pkt = new CHYCAOutMessage();
    WriteFuture wf;
    byte bt[] = pkt.getContent();
    bt[0] = 0;

    pkt.setContent(bt);
    wf = session.write(pkt); // 发送消息
    wf.awaitUninterruptibly();
    Thread.sleep(1000);
  }
Ejemplo n.º 22
0
 public void getsendMessageNotimeOut(Integer keys, Object message) {
   IoSession session = getSession(keys);
   log.info("反向发送消息到客户端Session---key=" + keys + "----------消息=" + message);
   if (MemoryData.minaClientSendTime.get(keys) != null
       && new Date().getTime() - MemoryData.minaClientSendTime.get(keys).getTime() > 1000 * 60
       && session.isConnected()) {
     System.out.println("发送消息----------------------------");
     JsonConfig config = new JsonConfig();
     config.registerDefaultValueProcessor(Integer.class, new MyDefaultIntegerValueProcessor());
     JSONObject json = JSONObject.fromObject(message, config);
     log.info("转化后的json的内容:" + json);
     session.write(json);
   }
 }
Ejemplo n.º 23
0
  public void deliver(Packet packet) throws UnauthorizedException {
    if (isClosed()) {
      // OF-857: Do not allow the backup deliverer to recurse
      if (backupDeliverer == null) {
        Log.error("Failed to deliver packet: " + packet.toXML());
        throw new IllegalStateException("Connection closed");
      }
      // attempt to deliver via backup only once
      PacketDeliverer backup = backupDeliverer;
      backupDeliverer = null;
      backup.deliver(packet);
    } else {
      boolean errorDelivering = false;
      IoBuffer buffer = IoBuffer.allocate(4096);
      buffer.setAutoExpand(true);
      try {
        // OF-464: if the connection has been dropped, fail over to backupDeliverer (offline)
        if (!ioSession.isConnected()) {
          throw new IOException("Connection reset/closed by peer");
        }
        XMLWriter xmlSerializer =
            new XMLWriter(new ByteBufferWriter(buffer, encoder.get()), new OutputFormat());
        xmlSerializer.write(packet.getElement());
        xmlSerializer.flush();
        if (flashClient) {
          buffer.put((byte) '\0');
        }
        buffer.flip();

        ioSessionLock.lock();
        try {
          ioSession.write(buffer);
        } finally {
          ioSessionLock.unlock();
        }
      } catch (Exception e) {
        Log.debug("Error delivering packet:\n" + packet, e);
        errorDelivering = true;
      }
      if (errorDelivering) {
        close();
        // Retry sending the packet again. Most probably if the packet is a
        // Message it will be stored offline
        backupDeliverer.deliver(packet);
      } else {
        session.incrementServerPacketCount();
      }
    }
  }
Ejemplo n.º 24
0
 @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 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);
   }
 }
Ejemplo n.º 26
0
  @Override
  public void messageReceived(IoSession session, Object message) throws Exception {
    // 接收客户端的数据
    IoBuffer ioBuffer = (IoBuffer) message;
    byte[] byteArray = new byte[ioBuffer.limit()];
    ioBuffer.get(byteArray, 0, ioBuffer.limit());
    System.out.println("messageReceived:" + new String(byteArray, "UTF-8"));

    // 发送到客户端
    byte[] responseByteArray = "你好".getBytes("UTF-8");
    IoBuffer responseIoBuffer = IoBuffer.allocate(responseByteArray.length);
    responseIoBuffer.put(responseByteArray);
    responseIoBuffer.flip();
    session.write(responseIoBuffer);
  }
 /**
  * 发送登录消息
  *
  * @param userName 用户名
  * @param password 密码
  */
 public boolean sendLoginMessage(String userName, String password) {
   STEPParser app = ParserConfig.getInstance().getStep();
   Message message =
       StepMessage.getLoginMessage(app, ExpressConstant.HEARTBEATRATE, userName, password);
   session.write(message);
   try {
     doLock();
   } catch (InterruptedException e) {
     log.error("Send Login Message InterruptedException: ", e);
   }
   if (isLockOk()) { // 登录成功开启定时心跳发送
     healthDaemon = new HealthDaemon(session);
   }
   return isLockOk();
 }
Ejemplo n.º 28
0
 @SuppressWarnings("rawtypes")
 private void sendErrorResponse(final IoSession session, final RequestWrapper request) {
   ResponseWrapper responseWrapper =
       new ResponseWrapper(request.getId(), request.getCodecType(), request.getProtocolType());
   responseWrapper.setException(
       new Exception("server threadpool full,maybe because server is slow or too many requests"));
   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: " + request.getId());
           }
         }
       });
 }
Ejemplo n.º 29
0
 public void process(String response) {
   // IoSession session = response.getSession();
   // String sourceStr = response.getSourceStr();
   StringBuffer buff = new StringBuffer();
   buff.append(response.substring(10, 18))
       .append(response.substring(2, 10))
       .append("C001")
       .append(Tools.fillNBitBefore(Integer.toHexString(SerialUtil.getInt()), 8, "0"))
       .append("00000005")
       .append(response.substring(22, 30))
       .append("00");
   buff.append(Tools.getCheckCode(buff.toString())).append("5D");
   String res = Tools.getReverTransferContent("5B" + buff.toString());
   session.write(res);
   count++;
   // log.info("--应答--[{}]",res);
 }
Ejemplo n.º 30
0
  public void getsendMessage(Integer keys, Object message) {
    log.info("SessionMap.map.size:" + map.size());

    IoSession session = getSession(keys);
    //		sdfdg(message);
    log.info("反向发送消息到客户端Session---key=" + keys + "----------消息=" + message);
    if (session == null || !session.isConnected()) {
      againSendMessage(keys, message);
      return;
    } else {
      log.info("发送消息----------------------------");
      JsonConfig config = new JsonConfig();
      config.registerDefaultValueProcessor(Integer.class, new MyDefaultIntegerValueProcessor());
      JSONObject json = JSONObject.fromObject(message, config);
      log.info("转化后的json的内容:" + json);
      session.write(json);
    }
  }