예제 #1
0
 private Socket getSocket(InetAddress addr, int portNo) {
   Socket socket = null;
   if (sockets.containsKey(addr) == true) {
     socket = sockets.get(addr);
     // check the status of the socket
     if (socket.isConnected() == false
         || socket.isInputShutdown() == true
         || socket.isOutputShutdown() == true
         || socket.getPort() != portNo) {
       // if socket is not suitable, then create a new socket
       sockets.remove(addr);
       try {
         socket.shutdownInput();
         socket.shutdownOutput();
         socket.close();
         socket = new Socket(addr, portNo);
         sockets.put(addr, socket);
       } catch (IOException e) {
         Log.e("getSocket: when closing and removing", "");
       }
     }
   } else {
     try {
       socket = new Socket(addr, portNo);
       sockets.put(addr, socket);
     } catch (IOException e) {
       Log.e("getSocket: when creating", "");
     }
   }
   return socket;
 }
 /** {@inheritDoc} */
 @Override
 public AsyncSocketChannelImpl shutdown(ShutdownType how) throws IOException {
   final Socket socket = channel.socket();
   try {
     if (how == ShutdownType.READ || how == ShutdownType.BOTH) {
       if (!socket.isInputShutdown()) {
         socket.shutdownInput();
         key.selected(OP_READ);
       }
     }
     if (how == ShutdownType.WRITE || how == ShutdownType.BOTH) {
       if (!socket.isOutputShutdown()) {
         socket.shutdownOutput();
         key.selected(OP_WRITE);
       }
     }
   } catch (SocketException e) {
     if (!socket.isConnected()) {
       throw Util.initCause(new NotYetConnectedException(), e);
     }
     if (socket.isClosed()) {
       throw Util.initCause(new ClosedChannelException(), e);
     }
     throw e;
   }
   return this;
 }
 public void message(String name, String msg) throws IOException {
   if (socket.isOutputShutdown()) {
     throw new IOException("Outbound socket is closed");
   }
   output.println(ProtocolStrings.MESSAGE + name + "#" + msg);
   // needs to work on it
 }
예제 #4
0
  public boolean closeClient() {
    try {

      LogUtil.log(this.clientId, "Closing ClientHandler Streams");
      LogUtil.log(this.clientId, "Closing ClientHandler Socket");

      this.unregisterClient();

      if (client != null) {
        client.close();

        if (!client.isInputShutdown()) this.client.shutdownInput();
        if (!client.isOutputShutdown()) this.client.shutdownOutput();
      }

      this.isRunning = false;
      LogUtil.log(this.clientId, "Closed ClientHandler Streams/Sockets");
      return true;
    } catch (SocketException e) {
      this.isRunning = false;
      LogUtil.log(this.clientId, "Closed Reading Socket");
      return true;
    } catch (IOException e) {
      LogUtil.log(this.clientId, "Could not close Client socket " + client.toString());
      return false;
    }
  }
 @Override
 public boolean isConnected() {
   return socket != null
       && !socket.isClosed()
       && socket.isConnected()
       && !socket.isOutputShutdown();
 }
  protected Socket borrowSocket() throws IOException {
    Socket socket = socketBlockingQueue.poll();

    if (socket != null) {
      if (socket.isClosed()
          || !socket.isConnected()
          || socket.isInputShutdown()
          || socket.isOutputShutdown()) {

        try {
          socket.close();
        } catch (IOException ioe) {
          if (_log.isWarnEnabled()) {
            _log.warn(ioe, ioe);
          }
        }

        socket = null;
      }
    }

    if (socket == null) {
      socket = new Socket();

      socket.connect(socketAddress);
    }

    return socket;
  }
  public void outputConnected(String name) throws IOException {
    if (socket.isOutputShutdown()) {
      throw new IOException("Outbound socket is closed");
    }

    output.println(ProtocolStrings.CONNECT + name + ",");
    // needs to work on it
  }
예제 #8
0
    private boolean windowCommand(Socket client, String command, String parameters) {
      boolean success = true;
      BufferedWriter out = null;

      try {
        // Find the hash code of the window
        int index = parameters.indexOf(' ');
        if (index == -1) {
          index = parameters.length();
        }
        final String code = parameters.substring(0, index);
        int hashCode = (int) Long.parseLong(code, 16);

        // Extract the command's parameter after the window description
        if (index < parameters.length()) {
          parameters = parameters.substring(index + 1);
        } else {
          parameters = "";
        }

        final View window = findWindow(hashCode);
        if (window == null) {
          return false;
        }

        // call stuff
        final Method dispatch =
            ViewDebug.class.getDeclaredMethod(
                "dispatchCommand", View.class, String.class, String.class, OutputStream.class);
        dispatch.setAccessible(true);
        dispatch.invoke(
            null,
            window,
            command,
            parameters,
            new UncloseableOutputStream(client.getOutputStream()));

        if (!client.isOutputShutdown()) {
          out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
          out.write("DONE\n");
          out.flush();
        }

      } catch (Exception e) {
        Log.w(LOG_TAG, "Could not send command " + command + " with parameters " + parameters, e);
        success = false;
      } finally {
        if (out != null) {
          try {
            out.close();
          } catch (IOException e) {
            success = false;
          }
        }
      }

      return success;
    }
예제 #9
0
 public static void closeSocket(final Socket socket) {
   if (!socket.isClosed()) {
     try {
       if (!socket.isOutputShutdown()) {
         socket.shutdownInput();
       }
       if (!socket.isInputShutdown()) {
         socket.shutdownInput();
       }
       socket.close();
     } catch (IOException e) {
       e.printStackTrace();
       logger.severe(e.getMessage());
     }
   }
 }
예제 #10
0
 public void disconnect() {
   if (m_connConfigd) {
     if (connected) {
       try {
         if (!socket.isInputShutdown()) socket.shutdownInput();
         if (!socket.isOutputShutdown()) socket.shutdownOutput();
         socket.close();
       } catch (IOException eClose) {
         s_logger.error("Error closing TCP: " + eClose);
       }
       inputStream = null;
       outputStream = null;
       connected = false;
       socket = null;
     }
   }
 }
  /** Close left-over sockets, streams and so on. */
  public void cleanup() {
    if (socket != null && socket.isConnected() && !socket.isClosed()) {
      try {
        if (socket != null && !socket.isOutputShutdown()) {
          socket.shutdownOutput();
        }
        if (socket != null && !socket.isInputShutdown()) {
          socket.shutdownInput();
        }
        if (socket != null && !socket.isClosed()) {
          socket.close();
        }

        if (bufferedInputStream != null) {
          bufferedInputStream.close();
          bufferedInputStream = null;
        }
        if (gzipInputStream != null) {
          gzipInputStream.close();
          gzipInputStream = null;
        }
        if (inputStream != null) {
          inputStream.close();
          inputStream = null;
        }
        if (gzipOutputStream != null) {
          gzipOutputStream.close();
          gzipOutputStream = null;
        }
        if (bufferedOutputStream != null) {
          bufferedOutputStream.close();
          bufferedOutputStream = null;
        }
        if (outputStream != null) {
          outputStream.close();
          outputStream = null;
        }
      } catch (Exception e) {
        baseStep.logError("Error closing socket", e);
      }
    }
  }
예제 #12
0
  @Override
  public InputStream getStream(String request) throws Exception {
    byte[] path = getAbsolute(request).getBytes();

    Socket s = socketPool.poll();
    if (s == null || s.isClosed() || s.isOutputShutdown() || s.isInputShutdown()) {
      s = new Socket();
      s.connect(address);
    }

    DataOutputStream o = new DataOutputStream(s.getOutputStream());
    o.writeInt(path.length);
    o.write(path);
    o.flush();

    DataInputStream i = new DataInputStream(s.getInputStream());
    int size = i.readInt();

    return new SocketInputStream(s, size, socketPool);
  }
예제 #13
0
  public boolean sendMsg(String msg) {

    LogUtil.logI(TAG, "send Message = " + msg);

    if (null == mSocket || null == mSocket.get()) {

      return false;
    }

    Socket soc = mSocket.get();

    if (soc == null) return false;

    try {

      if (!soc.isClosed() && !soc.isOutputShutdown()) {

        OutputStream os = soc.getOutputStream();

        String message = msg + "\r\n";

        os.write(message.getBytes("utf-8"));

        os.flush();

        sendTime = System.currentTimeMillis();

      } else {

        return false;
      }

    } catch (IOException e) {

      e.printStackTrace();

      return false;
    }

    return true;
  }
  protected void returnSocket(Socket socket, boolean forceCloseSocket) {
    boolean pooled = false;

    if (!forceCloseSocket
        && socket.isConnected()
        && !socket.isInputShutdown()
        && !socket.isOutputShutdown()) {

      pooled = socketBlockingQueue.offer(socket);
    }

    if (!pooled) {
      try {
        socket.close();
      } catch (IOException ioe) {
        if (_log.isWarnEnabled()) {
          _log.warn(ioe, ioe);
        }
      }
    }
  }
  @Override
  protected void handleConnection() {
    try {
      if (_commands.isEmpty()) {
        return;
      }

      _logger.trace("Waiting for connection");

      Socket clientSocket = getServerSocket().accept();

      _logger.trace("Got connection, sending...{}", _commands.size());

      String[] array = null;

      synchronized (this) {
        array = new String[_commands.size()];
        _commands.toArray(array);
        _commands.clear();
      }

      if (array != null) {
        _logger.debug("firing event {}", array.length);

        _messageSender.execute(new MessageSender(clientSocket, array));
      }

      if (clientSocket.isOutputShutdown()) {
        _logger.debug("Output shutdown.");
      } else {
        _logger.debug("Output not shutdown");
      }

      _logger.trace("Done sending!");
    } catch (SocketException se) {
      _logger.error(se.getMessage());
    } catch (IOException e) {
      _logger.error(e.getMessage(), e);
    }
  }
예제 #16
0
  public synchronized Socket getSocket() {
    if (serverSocket == null) {
      try {
        serverSocket = getSocket("rqm5.allengeary.com", 9443, true);
      } catch (Exception e) {
        log.fatal("Couold not connect to RQM server", e);
      }
    }

    if (serverSocket.isClosed()
        || serverSocket.isInputShutdown()
        || serverSocket.isOutputShutdown()
        || !serverSocket.isConnected()) {
      try {
        serverSocket = getSocket("rqm5.allengeary.com", 9443, true);
      } catch (Exception e) {
        log.fatal("Couold not connect to RQM server", e);
      }
    }

    return serverSocket;
  }
예제 #17
0
  /** {@inheritDoc} */
  public void closeChannel(SelectableChannel channel) {
    // channel could be either SocketChannel or ServerSocketChannel
    if (channel instanceof SocketChannel) {
      Socket socket = ((SocketChannel) channel).socket();

      try {
        if (!socket.isInputShutdown()) socket.shutdownInput();
      } catch (IOException e) {
        logger.log(Level.FINEST, "Unexpected exception during channel inputShutdown", e);
      }

      try {
        if (!socket.isOutputShutdown()) socket.shutdownOutput();
      } catch (IOException e) {
        logger.log(Level.FINEST, "Unexpected exception during channel outputShutdown", e);
      }

      try {
        socket.close();
      } catch (IOException e) {
        logger.log(Level.FINEST, "Unexpected exception during socket close", e);
      }
    }

    try {
      channel.close();
    } catch (IOException e) {
      logger.log(Level.FINEST, "Unexpected exception during channel close", e);
    }

    if (asyncQueueReader != null) {
      asyncQueueReader.onClose(channel);
    }

    if (asyncQueueWriter != null) {
      asyncQueueWriter.onClose(channel);
    }
  }
 @Override
 public boolean isOutputShutdown() {
   return sock.isOutputShutdown();
 }
    void cleanupChannel(final Channel ch, final Runnable callback) {

      if (null == ch) {
        // not expected
        logger.warn("null channel passed to cleanupChannel()", new Throwable());
        return;
      }

      if (Thread.currentThread() != this) {
        if (logger.isDebugEnabled()) {
          logger.debug("queue'ing channel close operation");
        }

        addSelectorTask(
            new Runnable() {
              @Override
              public void run() {
                CommThread.this.cleanupChannel(ch, callback);
              }
            });
        return;
      }

      try {
        if (ch instanceof SelectableChannel) {
          SelectableChannel sc = (SelectableChannel) ch;

          try {
            SelectionKey sk = sc.keyFor(selector);
            if (sk != null) {
              sk.attach(null);
              sk.cancel();
            }
          } catch (Exception e) {
            logger.warn("Exception trying to clear selection key", e);
          }
        }

        if (ch instanceof SocketChannel) {
          SocketChannel sc = (SocketChannel) ch;

          Socket s = sc.socket();

          if (null != s) {
            synchronized (s) {
              if (s.isConnected()) {
                try {
                  if (!s.isOutputShutdown()) {
                    s.shutdownOutput();
                  }
                } catch (Exception e) {
                  logger.warn("Exception trying to shutdown socket output: " + e.getMessage());
                }

                try {
                  if (!s.isClosed()) {
                    s.close();
                  }
                } catch (Exception e) {
                  logger.warn("Exception trying to close() socket: " + e.getMessage());
                }
              }
            }
          }
        } else if (ch instanceof ServerSocketChannel) {
          ServerSocketChannel ssc = (ServerSocketChannel) ch;

          try {
            ssc.close();
          } catch (Exception e) {
            logger.warn("Exception trying to close() server socket" + e.getMessage());
          }
        }

        try {
          ch.close();
        } catch (Exception e) {
          logger.warn("Exception trying to close channel", e);
        }
      } catch (Exception e) {
        // this is just a catch all to make sure that no exceptions will be thrown by this method,
        // please do not remove
        logger.error("Unhandled exception in cleanupChannel()", e);
      } finally {
        try {
          if (callback != null) {
            callback.run();
          }
        } catch (Throwable t) {
          logger.error("Unhandled exception in cleanupChannel callback.", t);
        }
      }
    }
예제 #20
0
 /** Returns true if this connection is alive. */
 public boolean isAlive() {
   return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown();
 }
예제 #21
0
 /**
  * Returns true if this connection is eligible to be recycled. This is like {@link #isStale}
  * except that it doesn't try to actually perform any I/O.
  */
 protected boolean isEligibleForRecycling() {
   return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown();
 }
예제 #22
0
  @Test
  public void testHalfClose() throws Exception {
    ServerSocket connector = new ServerSocket(0);

    Socket client = new Socket("localhost", connector.getLocalPort());
    Socket server = connector.accept();

    // we can write both ways
    client.getOutputStream().write(1);
    assertEquals(1, server.getInputStream().read());
    server.getOutputStream().write(1);
    assertEquals(1, client.getInputStream().read());

    // shutdown output results in read -1
    client.shutdownOutput();
    assertEquals(-1, server.getInputStream().read());

    // Even though EOF has been read, the server input is not seen as shutdown
    assertFalse(server.isInputShutdown());

    // and we can read -1 again
    assertEquals(-1, server.getInputStream().read());

    // but cannot write
    try {
      client.getOutputStream().write(1);
      fail("exception expected");
    } catch (SocketException e) {
    }

    // but can still write in opposite direction.
    server.getOutputStream().write(1);
    assertEquals(1, client.getInputStream().read());

    // server can shutdown input to match the shutdown out of client
    server.shutdownInput();

    // now we EOF instead of reading -1
    try {
      server.getInputStream().read();
      fail("exception expected");
    } catch (SocketException e) {
    }

    // but can still write in opposite direction.
    server.getOutputStream().write(1);
    assertEquals(1, client.getInputStream().read());

    // client can shutdown input
    client.shutdownInput();

    // now we EOF instead of reading -1
    try {
      client.getInputStream().read();
      fail("exception expected");
    } catch (SocketException e) {
    }

    // But we can still write at the server (data which will never be read)
    server.getOutputStream().write(1);

    // and the server output is not shutdown
    assertFalse(server.isOutputShutdown());

    // until we explictly shut it down
    server.shutdownOutput();

    // and now we can't write
    try {
      server.getOutputStream().write(1);
      fail("exception expected");
    } catch (SocketException e) {
    }

    // but the sockets are still open
    assertFalse(client.isClosed());
    assertFalse(server.isClosed());

    // but if we close one end
    client.close();

    // it is seen as closed.
    assertTrue(client.isClosed());

    // but not the other end
    assertFalse(server.isClosed());

    // which has to be closed explictly
    server.close();
    assertTrue(server.isClosed());
  }
예제 #23
0
 @Override
 public boolean isOutputShutdown() {
   return socket.isOutputShutdown() || !isActive();
 }
예제 #24
0
    /**
     * 处理联通上行信息
     *
     * @throws IOException 接收联通上行时有可能出现的IO流异常
     */
    private void executeMO() throws IOException {
      boolean isUnbind = false; // 收到unbind命令后,退出循环
      unicomIn = new DataInputStream(socket.getInputStream());
      spout = new DataOutputStream(socket.getOutputStream());
      // 读取联通发送来的字节流
      while (!isUnbind
          && !socket.isClosed()
          && socket.isConnected()
          && !socket.isInputShutdown()
          && !socket.isOutputShutdown()) {
        SGIPCommand command = null;
        try {
          command = read(unicomIn);
        } catch (IOException ex) {
          log.info("socket.getInputStream().available():" + socket.getInputStream().available());
          log.info("socket.isClosed:" + socket.isClosed()); // false
          log.info("socket.isConnected:" + socket.isConnected()); // true
          log.info("socket.isInputShutdown:" + socket.isInputShutdown()); // false
          log.info("socket.isOutputShutdown:" + socket.isOutputShutdown()); // false
          throw ex;
        }

        log.info(
            "【"
                + Thread.currentThread().getName()
                + "收到SMG "
                + SGIPCommandDefine.getCommandName(this.header.getCommandId())
                + "命令】,{长度="
                + command.header.getTotalmsglen()
                + "序列="
                + command.header.getSequenceNumber()
                + "}");

        switch (Bytes4ToInt(command.header.getCommandId())) {
            // -----------------------------------
          case 0x1: // 联通向SP发送的绑定命令
            log.info("收到SMG ->Bind命令");
            Bind bind = (Bind) command;
            log.info("LoginType:" + bind.getLoginType());
            log.info("LoginName:" + bind.getLoginName());
            log.info("LoginPassword:"******"smg loginfo:" + bind.getLoginName()+ "   " +
              // bind.getLoginPassword());
              // System.out.println("spcheck loginfo:"+ UnicomSPMonitor.smgLoginUserName + "   "+
              // UnicomSPMonitor.smgLoginPassword);
              if (bind.getLoginName().equals(UnicomSPMonitor.smgLoginUserName)
                  && bind.getLoginPassword().equals(UnicomSPMonitor.smgLoginPassword)) {
                log.info("SMG登陆SP,验证通过!");
                bindresp.setResult((byte) 0);
              } else {
                log.info("SMG登陆SP验证失败,SMG使用的用户名与密码与SP配置的参数不匹配!");
                bindresp.setResult((byte) 1);
              }
              bindresp.write(spout);
              log.info("Bind_Resp响应码:" + bindresp.getResult());
            }
            break;
            // ------------------------------------
          case 0x2: // 联通向SP发送的注销绑定命令
            // 响应
            log.info("收到SMG ->Unbind命令");
            UnbindResp resp = new UnbindResp(command.header.getUnicomSN());
            resp.write(spout);
            isUnbind = true;
            break;
            // ------------------------------------
          case 0x4: // 联通向SP上行一条用户短信
            log.info("收到SMG ->Deliver命令");
            Deliver deliver = (Deliver) command;
            log.info("SPNumber:" + deliver.getSPNumber());
            log.info("UserNumber:" + deliver.getUserNumber());
            log.info("MessageContent:" + deliver.getMessageContent());
            log.info("LinkID:" + deliver.getLinkID());
            // 收到响应
            DeliverResp deliverresp = new DeliverResp(command.header.getUnicomSN());
            deliverresp.setResult((byte) 0);
            deliverresp.write(spout);
            try {
              deliver(deliver); // 上行转发
            } catch (Exception ex) {
              ex.printStackTrace();
            }
            break;
            // -------------------------------------
          case 0x5: // 联通向SP报告之前一条MT的状态
            log.info("收到SMG ->Report命令");
            final Report report = (Report) command;
            log.info("ReportType:" + report.getReportType());
            log.info("UserNumber:" + report.getUserNumber());
            log.info("State:" + report.getState());
            log.info("ErrorCode:" + report.getErrorCode());
            // 返回响应
            ReportResp reportResp = new ReportResp(command.header.getUnicomSN());
            reportResp.setResult((byte) 0);
            reportResp.write(spout);
            if (report.getReportType() == 0) { // 对先前的一条Submit命令的状态报告
              try {
                report(report);
              } catch (Exception ex) {
                ex.printStackTrace();
              }
            }
            break;
            // --------------------------------------
          case 0x11: // 联通向SP报告一条手机用户的状态信息
            log.info("收到SMG ->UserRpt命令");
            UserRpt userRpt = (UserRpt) command;
            log.info("SPNumber:" + userRpt.getSPNumber());
            log.info("UserNumber:" + userRpt.getUserNumber());
            log.info("UserCondition:" + userRpt.getUserCondition());
            // 响应
            UserRptResp userRptresp = new UserRptResp(command.header.getUnicomSN());
            userRptresp.setResult((byte) 0);
            userRptresp.write(spout);

            break;
          default:
            log.error("error!! -->default:" + Bytes4ToInt(command.header.getCommandId()));
            break;
        }
      }

      log.info("socket.isClosed:" + socket.isClosed());
      log.info("socket.isClosed:" + socket.isConnected());
      log.info("socket.isInputShutdown:" + socket.isInputShutdown());
      log.info("socket.isOutputShutdown:" + socket.isOutputShutdown());
    }