Java Code Examples for java.net.Socket#shutdownOutput()

The following examples show how to use java.net.Socket#shutdownOutput() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Bootstrap.java    From opencron with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @throws Exception
 */

public void shutdown() throws Exception {
    /**
     * connect to startup socket and send stop command。。。。。。
     */
    Socket socket = new Socket("localhost",Integer.valueOf(System.getProperty("opencron.shutdown")));
    OutputStream os = socket.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    InputStream is = socket.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    pw.write(shutdown);
    pw.flush();
    socket.shutdownOutput();
    String reply = null;
    while (!((reply = br.readLine()) == null)) {
        logger.info("[opencron]shutdown:{}" + reply);
    }
    br.close();
    is.close();
    pw.close();
    os.close();
    socket.close();
}
 
Example 2
Source File: SocketUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static void closeQuietly(final Socket socket) {
    if (socket == null) {
        return;
    }

    try {
        try {
            // Can't shutdown input/output individually with secure sockets
            if (!(socket instanceof SSLSocket)) {
                if (!socket.isInputShutdown()) {
                    socket.shutdownInput();
                }
                if (!socket.isOutputShutdown()) {
                    socket.shutdownOutput();
                }
            }
        } finally {
            if (!socket.isClosed()) {
                socket.close();
            }
        }
    } catch (final Exception ex) {
        logger.debug("Failed to close socket due to: " + ex, ex);
    }
}
 
Example 3
Source File: SocketUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public static void closeQuietly(final Socket socket) {
    if (socket == null) {
        return;
    }

    try {
        try {
            // can't shudown input/output individually with secure sockets
            if ((socket instanceof SSLSocket) == false) {
                if (socket.isInputShutdown() == false) {
                    socket.shutdownInput();
                }
                if (socket.isOutputShutdown() == false) {
                    socket.shutdownOutput();
                }
            }
        } finally {
            if (socket.isClosed() == false) {
                socket.close();
            }
        }
    } catch (final Exception ex) {
        logger.debug("Failed to close socket due to: " + ex, ex);
    }
}
 
Example 4
Source File: MockWebServer.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
private void writeResponse(final Socket socket) throws IOException {
    logger.debug("Socket response for resource {}", resource.getFilename());
    final OutputStream out = socket.getOutputStream();
    out.write(STATUS_LINE.getBytes());
    out.write(header("Content-Length", this.resource.contentLength()));
    out.write(header("Content-Type", this.contentType));
    out.write(SEPARATOR.getBytes());

    final byte[] buffer = new byte[BUFFER_SIZE];
    try (final InputStream in = this.resource.getInputStream()) {
        int count = 0;
        while ((count = in.read(buffer)) > -1) {
            out.write(buffer, 0, count);
        }
    }
    logger.debug("Wrote response for resource {} for {}",
            resource.getFilename(),
            resource.contentLength());

    socket.shutdownOutput();
}
 
Example 5
Source File: SocketShutdownOutputByPeerTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public void testShutdownOutput(ServerBootstrap sb) throws Throwable {
    TestHandler h = new TestHandler();
    Socket s = new Socket();
    try {
        sb.childHandler(h).childOption(ChannelOption.ALLOW_HALF_CLOSURE, true).bind().sync();

        s.connect(addr, 10000);
        s.getOutputStream().write(1);

        assertEquals(1, (int) h.queue.take());

        assertTrue(h.ch.isOpen());
        assertTrue(h.ch.isActive());
        assertFalse(h.ch.isInputShutdown());
        assertFalse(h.ch.isOutputShutdown());

        s.shutdownOutput();

        h.halfClosure.await();

        assertTrue(h.ch.isOpen());
        assertTrue(h.ch.isActive());
        assertTrue(h.ch.isInputShutdown());
        assertFalse(h.ch.isOutputShutdown());
        assertEquals(1, h.closure.getCount());
        Thread.sleep(100);
        assertEquals(1, h.halfClosureCount.intValue());
    } finally {
        s.close();
    }
}
 
Example 6
Source File: SocketShutdownOutputByPeerTest.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public void testShutdownOutputWithoutOption(ServerBootstrap sb) throws Throwable {
    TestHandler h = new TestHandler();
    Socket s = new Socket();
    try {
        sb.childHandler(h).bind().sync();

        s.connect(addr, 10000);
        s.getOutputStream().write(1);

        assertEquals(1, (int) h.queue.take());

        assertTrue(h.ch.isOpen());
        assertTrue(h.ch.isActive());
        assertFalse(h.ch.isInputShutdown());
        assertFalse(h.ch.isOutputShutdown());

        s.shutdownOutput();

        h.closure.await();

        assertFalse(h.ch.isOpen());
        assertFalse(h.ch.isActive());
        assertTrue(h.ch.isInputShutdown());
        assertTrue(h.ch.isOutputShutdown());

        assertEquals(1, h.halfClosure.getCount());
        Thread.sleep(100);
        assertEquals(0, h.halfClosureCount.intValue());
    } finally {
        s.close();
    }
}
 
Example 7
Source File: Kelinci.java    From kelinci with Apache License 2.0 5 votes vote down vote up
/**
 * Method to run in a thread to accept requests coming
 * in over TCP and put them in a queue.
 */
private static void runServer() {

	try (ServerSocket ss = new ServerSocket(port)) {
		if (verbosity > 1)
			System.out.println("Server listening on port " + port);

		while (true) {
			Socket s = ss.accept();
			if (verbosity > 1)
				System.out.println("Connection established.");

			boolean status = false;
			if (requestQueue.size() < maxQueue) {
				status = requestQueue.offer(new FuzzRequest(s));
				if (verbosity > 1)
					System.out.println("Request added to queue: " + status);
			} 
			if (!status) {
				if (verbosity > 1)
					System.out.println("Queue full.");
				OutputStream os = s.getOutputStream();
				os.write(STATUS_QUEUE_FULL);
				os.flush();
				s.shutdownOutput();
				s.shutdownInput();
				s.close();
				if (verbosity > 1)
					System.out.println("Connection closed.");
			}
		}
	} catch (BindException be) {
		System.err.println("Unable to bind to port " + port);
		System.exit(1);
	} catch (Exception e) {
		System.err.println("Exception in request server");
		e.printStackTrace();
		System.exit(1);
	}
}
 
Example 8
Source File: TestSocketServlet.java    From appengine-java-vm-runtime with Apache License 2.0 5 votes vote down vote up
private void testShutDownAndClose(HttpServletResponse response)
    throws UnknownHostException, IOException {
  Socket socket = new Socket("10.1.1.1", 80);
  socket.shutdownInput();
  socket.shutdownOutput();
  socket.close();
}
 
Example 9
Source File: HttpProxyCacheServer.java    From DKVideoPlayer with Apache License 2.0 5 votes vote down vote up
private void closeSocketOutput(Socket socket) {
    try {
        if (!socket.isOutputShutdown()) {
            socket.shutdownOutput();
        }
    } catch (IOException e) {
        Logger.warn("Failed to close socket on proxy side: {}. It seems client have already closed connection.");
    }
}
 
Example 10
Source File: HttpProxyCacheServer.java    From AndroidVideoCache with Apache License 2.0 5 votes vote down vote up
private void closeSocketOutput(Socket socket) {
    try {
        if (!socket.isOutputShutdown()) {
            socket.shutdownOutput();
        }
    } catch (IOException e) {
        LOG.warn("Failed to close socket on proxy side: {}. It seems client have already closed connection.", e.getMessage());
    }
}
 
Example 11
Source File: HttpProxyCacheServer.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
private void closeSocketOutput(Socket socket) {
    try {
        if (!socket.isOutputShutdown()) {
            socket.shutdownOutput();
        }
    } catch (IOException e) {
        LOG.warn("Failed to close socket on proxy side: {}. It seems client have already closed connection.", e.getMessage());
    }
}
 
Example 12
Source File: HttpProxyCacheServer.java    From AndriodVideoCache with Apache License 2.0 5 votes vote down vote up
private void closeSocketOutput(Socket socket) {
    try {
        if (!socket.isOutputShutdown()) {
            socket.shutdownOutput();
        }
    } catch (IOException e) {
        KLog.w("Failed to close socket on proxy side: {}. It seems client have already closed connection.", e.getMessage());
    }
}
 
Example 13
Source File: HttpProxyCacheServer.java    From VideoOS-Android-SDK with GNU General Public License v3.0 5 votes vote down vote up
private void closeSocketOutput(Socket socket) {
    try {
        if (!socket.isOutputShutdown()) {
            socket.shutdownOutput();
        }
    } catch (IOException e) {
        VenvyLog.w("Failed to close socket on proxy side: {}. It seems client have already closed connection.", e.getMessage());
    }
}
 
Example 14
Source File: SocketShutdownOutputByPeerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public void testShutdownOutputWithoutOption(ServerBootstrap sb) throws Throwable {
    TestHandler h = new TestHandler();
    Socket s = new Socket();
    Channel sc = null;
    try {
        sc = sb.childHandler(h).bind().sync().channel();

        SocketUtils.connect(s, sc.localAddress(), 10000);
        s.getOutputStream().write(1);

        assertEquals(1, (int) h.queue.take());

        assertTrue(h.ch.isOpen());
        assertTrue(h.ch.isActive());
        assertFalse(h.ch.isInputShutdown());
        assertFalse(h.ch.isOutputShutdown());

        s.shutdownOutput();

        h.closure.await();

        assertFalse(h.ch.isOpen());
        assertFalse(h.ch.isActive());
        assertTrue(h.ch.isInputShutdown());
        assertTrue(h.ch.isOutputShutdown());

        assertEquals(1, h.halfClosure.getCount());
        Thread.sleep(100);
        assertEquals(0, h.halfClosureCount.intValue());
    } finally {
        if (sc != null) {
            sc.close();
        }
        s.close();
    }
}
 
Example 15
Source File: SocketShutdownOutputByPeerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public void testShutdownOutput(ServerBootstrap sb) throws Throwable {
    TestHandler h = new TestHandler();
    Socket s = new Socket();
    Channel sc = null;
    try {
        sc = sb.childHandler(h).childOption(ChannelOption.ALLOW_HALF_CLOSURE, true).bind().sync().channel();

        SocketUtils.connect(s, sc.localAddress(), 10000);
        s.getOutputStream().write(1);

        assertEquals(1, (int) h.queue.take());

        assertTrue(h.ch.isOpen());
        assertTrue(h.ch.isActive());
        assertFalse(h.ch.isInputShutdown());
        assertFalse(h.ch.isOutputShutdown());

        s.shutdownOutput();

        h.halfClosure.await();

        assertTrue(h.ch.isOpen());
        assertTrue(h.ch.isActive());
        assertTrue(h.ch.isInputShutdown());
        assertFalse(h.ch.isOutputShutdown());
        assertEquals(1, h.closure.getCount());
        Thread.sleep(100);
        assertEquals(1, h.halfClosureCount.intValue());
    } finally {
        if (sc != null) {
            sc.close();
        }
        s.close();
    }
}
 
Example 16
Source File: SocketServerFragment.java    From ScreenCapture with MIT License 4 votes vote down vote up
@Override
        public void run() {
            Bundle bundle = new Bundle();
            bundle.clear();
            OutputStream output;
            String str = "hello hehe";
            try {
                serverSocket = new ServerSocket(PORT);
                while (!stop) {
                    Log.d("WOW", "LOOP");
                    Message msg = new Message();
                    msg.what = 0x11;
                    try {
                        Socket socket = serverSocket.accept();
                        output = socket.getOutputStream();
                        output.write(str.getBytes("gbk"));
                        output.flush();
                        socket.shutdownOutput();
                        Log.d("WOW", "LOOP1111");

                        DataInputStream in = new DataInputStream(socket.getInputStream());
                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                        byte[] inputByte = new byte[2048];
                        byte[] finalByte = new byte[0];
                        int length = 0;
                        Log.d("WOW", "start to receive");
                        while ((length = in.read(inputByte, 0, inputByte.length)) > 0) {
//                            outputStream.write(inputByte, 0, length);
                            byte[] tmp = new byte[finalByte.length + length];
                            System.arraycopy(finalByte, 0, tmp, 0, finalByte.length);
                            System.arraycopy(inputByte, 0, tmp, finalByte.length, length);
                            finalByte = tmp;
                            Log.d("WOW", "final byte[] length:" + finalByte.length);
                        }

                        Log.d("WOW", "receiveddddddd");
                        Bitmap bmp = ImageUtils.byte2bitmap(finalByte);

                        // save bmp
                        Log.d("WOW", "get bmp:" + (bmp != null));
                        SimpleDateFormat date = new SimpleDateFormat("yyyyMMddhhmmss");
                        String fileName = getContext().getExternalFilesDir(null).getAbsolutePath()
                                + "/myScreenshots" + "/received_" + date.format(new Date()) + ".png";
                        Log.d("WOW", "save to " + fileName);
                        FileOutputStream fos = new FileOutputStream(fileName);
                        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);

                        in.close();
                        outputStream.close();


                        mHandler.sendMessage(msg);
//                        bff.close();
                        output.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
 
Example 17
Source File: GridNioSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Sends message and validates reply.
 *
 * @param port Port.
 * @param msg Message to send.
 */
private void validateSendMessage(int port, byte[] msg) {
    try {
        Socket s = createSocket();

        s.connect(new InetSocketAddress(U.getLocalHost(), port), 1000);

        try {
            s.getOutputStream().write(msg);

            byte[] res = new byte[MSG_SIZE];

            int rcvd = 0;

            InputStream inputStream = s.getInputStream();

            while (rcvd < res.length) {
                int cnt = inputStream.read(res, rcvd, res.length - rcvd);

                if (cnt == -1)
                    fail("Server closed connection before echo reply was fully sent");

                rcvd += cnt;
            }

            if (!(s instanceof SSLSocket)) {
                s.shutdownOutput();

                s.shutdownInput();
            }

            assertEquals(msg.length, res.length);

            for (int i = 0; i < msg.length; i++)
                assertEquals("Mismatch in position " + i, msg[i], res[i]);
        }
        finally {
            s.close();
        }
    }
    catch (Exception e) {
        fail("Exception while sending message: " + e.getMessage());
    }
}
 
Example 18
Source File: OkHttpClientTransportTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Test
public void proxy_500() throws Exception {
  ServerSocket serverSocket = new ServerSocket(0);
  InetSocketAddress targetAddress = InetSocketAddress.createUnresolved("theservice", 80);
  clientTransport = new OkHttpClientTransport(
      targetAddress,
      "authority",
      "userAgent",
      EAG_ATTRS,
      executor,
      socketFactory,
      sslSocketFactory,
      hostnameVerifier,
      ConnectionSpec.CLEARTEXT,
      DEFAULT_MAX_MESSAGE_SIZE,
      INITIAL_WINDOW_SIZE,
      HttpConnectProxiedSocketAddress.newBuilder()
          .setTargetAddress(targetAddress)
          .setProxyAddress(serverSocket.getLocalSocketAddress()).build(),
      tooManyPingsRunnable,
      DEFAULT_MAX_INBOUND_METADATA_SIZE,
      transportTracer,
      false);
  clientTransport.start(transportListener);

  Socket sock = serverSocket.accept();
  serverSocket.close();

  BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream(), UTF_8));
  assertEquals("CONNECT theservice:80 HTTP/1.1", reader.readLine());
  assertEquals("Host: theservice:80", reader.readLine());
  while (!"".equals(reader.readLine())) {}

  final String errorText = "text describing error";
  sock.getOutputStream().write("HTTP/1.1 500 OH NO\r\n\r\n".getBytes(UTF_8));
  sock.getOutputStream().write(errorText.getBytes(UTF_8));
  sock.getOutputStream().flush();
  sock.shutdownOutput();

  assertEquals(-1, sock.getInputStream().read());

  ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
  verify(transportListener, timeout(TIME_OUT_MS)).transportShutdown(captor.capture());
  Status error = captor.getValue();
  assertTrue("Status didn't contain error code: " + captor.getValue(),
      error.getDescription().contains("500"));
  assertTrue("Status didn't contain error description: " + captor.getValue(),
      error.getDescription().contains("OH NO"));
  assertTrue("Status didn't contain error text: " + captor.getValue(),
      error.getDescription().contains(errorText));
  assertEquals("Not UNAVAILABLE: " + captor.getValue(),
      Status.UNAVAILABLE.getCode(), error.getCode());
  sock.close();
  verify(transportListener, timeout(TIME_OUT_MS)).transportTerminated();
}
 
Example 19
Source File: EvolutionPanel.java    From iMetrica with GNU General Public License v3.0 4 votes vote down vote up
public void run()
     {
        System.out.println("start up IQ");
		try {
                       //
			// Launch IQFeed and Register the app with IQFeed.
// 			System.out.println("Launching IQConnect.");
// 			//Runtime.getRuntime().exec("/usr/bin/wine IQConnect.exe ‑product SIMON_OTZIGER_6345 -version 2.9.0.13 ‑login 422113 ‑password 76059316");
// 			System.out.println("Verifying if IQConnect is connected to the server");
// 			Thread.sleep(12000);
// 			// verify everything is ready to send commands.
// 			boolean bConnected = false;
// 			// connect to the admin port.
// 			Socket sockAdmin = new Socket(InetAddress.getByName("192.168.56.10"), 8300);
			
			System.out.println("Launching IQConnect.");
	
                        //Runtime.getRuntime().exec("/usr/bin/wine IQConnect.exe -product JEANPIERRE_ROBALO_11529 -version 2.9.0.13 ‑login 431660 ‑password 70433790");
                        Runtime.getRuntime().exec("/usr/bin/wine IQConnect.exe -product PRABIN_SETH_11606 -version 2.9.0.13 ‑login 438106 ‑password 64568341");
			System.out.println("Verifying if IQConnect is connected to the server");
			Thread.sleep(12000);
			//verify everything is ready to send commands.
			boolean bConnected = false;
			//connect to the admin port.
			Socket sockAdmin = new Socket(InetAddress.getByName("localhost"), 9300);			
			
			
			BufferedReader bufreadAdmin = new BufferedReader(new InputStreamReader(sockAdmin.getInputStream()));
			BufferedWriter bufwriteAdmin = new BufferedWriter(new OutputStreamWriter(sockAdmin.getOutputStream()));
			String sAdminLine = "";
			// loop while we are still connected to the admin port or until we are connected
			while (((sAdminLine = bufreadAdmin.readLine()) != null) && !bConnected)
			{
				System.out.println(sAdminLine);
				if (sAdminLine.indexOf(",Connected,") > -1)
				{
					System.out.println("IQConnect is connected to the server.");
					bConnected = true;
				}
				else if (sAdminLine.indexOf(",Not Connected,") > -1)
				{
					System.out.println("IQConnect is Not Connected.\r\nSending connect command.");
					bufwriteAdmin.write("S,CONNECT\r\n");
					bufwriteAdmin.flush();
				}
			}
			// cleanup admin port connection
			sockAdmin.shutdownOutput();
			sockAdmin.shutdownInput();
			sockAdmin.close();
			bufreadAdmin.close();
			bufwriteAdmin.close();

			// at this point, we are connected and the feed is ready.
			int total_num_assets = 8;
			
// 			for(int i = 0; i < n_basket; i++)
// 			{total_num_assets = total_num_assets + ppms[i].name.length;}
// 			
// 			total_num_assets = ppms.length*3; 
			s_outs = new BufferedWriter[total_num_assets];
			s_ins = new BufferedReader[total_num_assets];
			Socket[] socks = new Socket[total_num_assets];
			
			for(int i = 0; i < total_num_assets; i++)
                       {
                         socks[i] = new Socket(InetAddress.getByName("localhost"), 9100);
	                 //socks[i] = new Socket(InetAddress.getByName("192.168.56.10"), 8100);
	                 s_ins[i] = new BufferedReader(new InputStreamReader(socks[i].getInputStream()));
	                 s_outs[i] = new BufferedWriter(new OutputStreamWriter(socks[i].getOutputStream()));
	                 // Set the lookup port to protocol 5.0 to allow for millisecond times, 
                         // market center, trade conditions, etc
                         s_outs[i].write("S,SET PROTOCOL,5.0\r\n");
                         s_outs[i].flush();   
	               }
                        
                     }
                     catch (Exception e)
		     {e.printStackTrace();}    
    
    
      }
 
Example 20
Source File: OkHttpClientTransportTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void proxy_500() throws Exception {
  ServerSocket serverSocket = new ServerSocket(0);
  clientTransport = new OkHttpClientTransport(
      InetSocketAddress.createUnresolved("theservice", 80),
      "authority",
      "userAgent",
      executor,
      sslSocketFactory,
      hostnameVerifier,
      ConnectionSpec.CLEARTEXT,
      DEFAULT_MAX_MESSAGE_SIZE,
      INITIAL_WINDOW_SIZE,
      new ProxyParameters(
          (InetSocketAddress) serverSocket.getLocalSocketAddress(), NO_USER, NO_PW),
      tooManyPingsRunnable,
      DEFAULT_MAX_INBOUND_METADATA_SIZE,
      transportTracer);
  clientTransport.start(transportListener);

  Socket sock = serverSocket.accept();
  serverSocket.close();

  BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream(), UTF_8));
  assertEquals("CONNECT theservice:80 HTTP/1.1", reader.readLine());
  assertEquals("Host: theservice:80", reader.readLine());
  while (!"".equals(reader.readLine())) {}

  final String errorText = "text describing error";
  sock.getOutputStream().write("HTTP/1.1 500 OH NO\r\n\r\n".getBytes(UTF_8));
  sock.getOutputStream().write(errorText.getBytes(UTF_8));
  sock.getOutputStream().flush();
  sock.shutdownOutput();

  assertEquals(-1, sock.getInputStream().read());

  ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
  verify(transportListener, timeout(TIME_OUT_MS)).transportShutdown(captor.capture());
  Status error = captor.getValue();
  assertTrue("Status didn't contain error code: " + captor.getValue(),
      error.getDescription().contains("500"));
  assertTrue("Status didn't contain error description: " + captor.getValue(),
      error.getDescription().contains("OH NO"));
  assertTrue("Status didn't contain error text: " + captor.getValue(),
      error.getDescription().contains(errorText));
  assertEquals("Not UNAVAILABLE: " + captor.getValue(),
      Status.UNAVAILABLE.getCode(), error.getCode());
  sock.close();
  verify(transportListener, timeout(TIME_OUT_MS)).transportTerminated();
}