@Test public void testHalfCloseClientServer() throws Exception { ServerSocketChannel connector = ServerSocketChannel.open(); connector.socket().bind(null); Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket(); client.setSoTimeout(1000); client.setSoLinger(false, -1); Socket server = connector.accept().socket(); server.setSoTimeout(1000); server.setSoLinger(false, -1); // Write from client to server client.getOutputStream().write(1); // Server reads assertEquals(1, server.getInputStream().read()); // Write from server to client with oshut server.getOutputStream().write(1); // System.err.println("OSHUT "+server); server.shutdownOutput(); // Client reads response assertEquals(1, client.getInputStream().read()); try { // Client reads -1 and does ishut assertEquals(-1, client.getInputStream().read()); assertFalse(client.isInputShutdown()); // System.err.println("ISHUT "+client); client.shutdownInput(); // Client ??? // System.err.println("OSHUT "+client); client.shutdownOutput(); // System.err.println("CLOSE "+client); client.close(); // Server reads -1, does ishut and then close assertEquals(-1, server.getInputStream().read()); assertFalse(server.isInputShutdown()); // System.err.println("ISHUT "+server); try { server.shutdownInput(); } catch (SocketException e) { // System.err.println(e); } // System.err.println("CLOSE "+server); server.close(); } catch (Exception e) { System.err.println(e); assertTrue(OS.IS_OSX); } }
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; } }
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; }
/** {@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; }
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; }
public boolean isConnected() { return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected() && !socket.isInputShutdown() && !socket.isOutputShutdown(); }
public void run() { Log.v(TAG, "entering client thread --> "); String message = null; try { Log.v(TAG, "server IP:" + mServerIP + ", SERVER_PORT" + SERVER_PORT); mSocket = new Socket(mServerIP, SERVER_PORT); mReader = new BufferedReader(new InputStreamReader(mSocket.getInputStream())); mWriter = new PrintWriter( new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream())), true); if (mHandler != null) { mHandler.sendMessage(Message.obtain(null, MSG_ON_SERVER_CONNECTED, message)); } while (true) { Log.v(TAG, "try to read from socket --> "); if (mSocket.isConnected() && !mSocket.isInputShutdown()) { message = mReader.readLine(); Log.v(TAG, "Read Message: " + message); if (message == null) { Log.v(TAG, "remote socket closed"); break; } else { if (mHandler != null) { mHandler.sendMessage(Message.obtain(null, MSG_ON_MESSAGE_ARRIVED, message)); } } } else { Log.v(TAG, "disconnected ir input shutdown, so quit!: "); break; } } } catch (UnknownHostException e) { e.printStackTrace(); } catch (ConnectException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { if (mReader != null) { mReader.close(); mReader = null; } if (mWriter != null) { mWriter.close(); mWriter = null; } mSocket = null; } catch (IOException e) { e.printStackTrace(); } Log.v(TAG, "exit client thread --> "); }
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()); } } }
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); } } }
@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); }
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); } } } }
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; }
/** {@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 isInputShutdown() { return sock.isInputShutdown(); }
/** Returns true if this connection is alive. */ public boolean isAlive() { return !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown(); }
@Override public void run() { String msg; while (!sock.isInputShutdown() && (running == true)) { try { Thread.sleep(100); } catch (InterruptedException e1) { e1.printStackTrace(); } try { msg = br.readLine(); if (msg != null) { logger.info("REQUEST: " + msg); if (msg.startsWith("?org.openmuc.mux.dataserver")) { out.println("!org.openmuc.mux.dataserver_response"); } else if (msg.startsWith("?get ")) { getReply(msg); } else if (msg.startsWith("?get_age ")) { getAge(msg); } else if (msg.startsWith("?get_value ")) { getValueReply(msg); } else if (msg.startsWith("?set_value ")) { setValueReply(msg); } else if (msg.startsWith("?get_all_values")) { getAllValuesReply(msg); } else if (msg.startsWith("?get_values ")) { getValuesReply(msg); } else if (msg.startsWith("?configure_report ")) { configureReport(msg); } else if (msg.startsWith("?get_directory")) { getDirectoryReply(msg); } else if (msg.startsWith("?disconnect")) { out.println("!DISCONNECTED"); sock.close(); running = false; } else { out.println("!ERROR"); } } else { logger.info("CLOSE SOCKET"); sock.close(); running = false; } } catch (InterruptedIOException iioe) { try { sock.close(); } catch (IOException e) { logger.error(e.getMessage()); } logger.info("Timeout occurred (60s) - killing connection"); break; } catch (Exception e) { logger.info(e.getMessage()); running = false; } /* create reports on demand */ // TODO Implement reporting with timer / separate thread // if (store.getStore() != null) { // for (Report report : reports) { // report.emitReport(out); // } // } // else { // if (reports.size() > 0) reports.clear(); // } } logger.info("CONNECTION CLOSED!"); server.connectionClosed(this); }
@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()); }
@Test public void testHalfCloseBadClient() throws Exception { ServerSocketChannel connector = ServerSocketChannel.open(); connector.socket().bind(null); Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket(); client.setSoTimeout(1000); client.setSoLinger(false, -1); Socket server = connector.accept().socket(); server.setSoTimeout(1000); server.setSoLinger(false, -1); // Write from client to server client.getOutputStream().write(1); // Server reads assertEquals(1, server.getInputStream().read()); // Write from server to client with oshut server.getOutputStream().write(1); // System.err.println("OSHUT "+server); server.shutdownOutput(); try { // Client reads response assertEquals(1, client.getInputStream().read()); // Client reads -1 assertEquals(-1, client.getInputStream().read()); assertFalse(client.isInputShutdown()); // Client can still write as we are half closed client.getOutputStream().write(1); // Server can still read assertEquals(1, server.getInputStream().read()); // Server now closes server.close(); // Client still reads -1 (not broken pipe !!) assertEquals(-1, client.getInputStream().read()); assertFalse(client.isInputShutdown()); Thread.sleep(100); // Client still reads -1 (not broken pipe !!) assertEquals(-1, client.getInputStream().read()); assertFalse(client.isInputShutdown()); // Client can still write data even though server is closed??? client.getOutputStream().write(1); // Client eventually sees Broken Pipe int i = 0; try { for (i = 0; i < 100000; i++) client.getOutputStream().write(1); Assert.fail(); } catch (IOException e) { } client.close(); } catch (Exception e) { System.err.println("PLEASE INVESTIGATE:"); e.printStackTrace(); } }
/** * 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(); }
public void run() { Socket socket = mWeakSocket.get(); InputStream is = null; if (null != socket) { try { is = socket.getInputStream(); byte[] buffer = new byte[1024 * 4]; int length = 0; while (!socket.isClosed() && !socket.isInputShutdown() && isStart && ((length = is.read(buffer)) != -1)) { if (length > 0) { String message = new String(Arrays.copyOf(buffer, length), "utf-8").trim(); Log.e("TURNTO", "message=" + message); if (message.equals("ok")) { Intent intent = new Intent(MessageReciver.HEART_BEAT_ACTION); sendBroadcast(intent); } else { MessageModel model = new MessageModel(); JSONObject jsonObject = new JSONObject(message); String action = jsonObject.getString("action"); if (action.equals(MessageUtil.MEMBER_CONTENT)) { model.messageStr = jsonObject.getString("data"); model.fromUserId = jsonObject.getString("uid"); model.toUserId = application.getInfoResult().data.user_info.user_id; model.type = "1"; model.timetemp = "" + System.currentTimeMillis(); model.status = ""; Log.i(TAG, "sendBroadcast"); Intent intent = new Intent(MessageReciver.MESSAGE_ACTION); intent.putExtra("message", model); sendBroadcast(intent); saveMessage(model); } } } } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { Log.i(TAG, "ReadMessageThread finished"); if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } releaseLastSocket(mWeakSocket); releaseLastSocket(mSocket); } } }
/** * 处理联通上行信息 * * @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()); }