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

The following examples show how to use java.net.Socket#getOutputStream() . 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: TestBlockReplacement.java    From RDFS with Apache License 2.0 6 votes vote down vote up
private boolean replaceBlock( Block block, DatanodeInfo source,
    DatanodeInfo sourceProxy, DatanodeInfo destination, int namespaceId) throws IOException {
  Socket sock = new Socket();
  sock.connect(NetUtils.createSocketAddr(
      destination.getName()), HdfsConstants.READ_TIMEOUT);
  sock.setKeepAlive(true);
  // sendRequest
  DataOutputStream out = new DataOutputStream(sock.getOutputStream());
  out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION);
  out.writeByte(DataTransferProtocol.OP_REPLACE_BLOCK);
  out.writeInt(namespaceId);
  out.writeLong(block.getBlockId());
  out.writeLong(block.getGenerationStamp());
  Text.writeString(out, source.getStorageID());
  sourceProxy.write(out);
  out.flush();
  // receiveResponse
  DataInputStream reply = new DataInputStream(sock.getInputStream());

  short status = reply.readShort();
  if(status == DataTransferProtocol.OP_STATUS_SUCCESS) {
    return true;
  }
  return false;
}
 
Example 2
Source File: LdapTimeoutTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public void run() {
    try {
        accepting = true;
        Socket socket = serverSock.accept();
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();

        // Read the LDAP BindRequest
        while (in.read() != -1) {
            in.skip(in.available());
            break;
        }

        // Write an LDAP BindResponse
        out.write(bindResponse);
        out.flush();
    } catch (IOException e) {
        // ignore
    }
}
 
Example 3
Source File: ProxyTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void smallBandwidth() throws Exception {
  server = new Server();
  int serverPort = server.init();
  server.setMode("stream");
  executor.execute(server);
  assertEquals("stream", server.mode());

  int bandwidth = 64 * 1024;
  proxy = new TrafficControlProxy(serverPort, bandwidth, 200, TimeUnit.MILLISECONDS);
  startProxy(proxy).get();
  client = new Socket("localhost", proxy.getPort());
  DataOutputStream clientOut = new DataOutputStream(client.getOutputStream());
  DataInputStream clientIn = new DataInputStream(client.getInputStream());

  clientOut.write(new byte[1]);
  clientIn.readFully(new byte[100 * 1024]);
  long start = System.nanoTime();
  clientIn.readFully(new byte[5 * bandwidth]);
  long stop = System.nanoTime();

  long bandUsed = ((5 * bandwidth) / ((stop - start) / TimeUnit.SECONDS.toNanos(1)));
  assertEquals(bandwidth, bandUsed, .5 * bandwidth);
}
 
Example 4
Source File: Endpoint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static Endpoint forSocket(final Socket s) {
    return new Endpoint() {
        @Override
        public InputStream getInputStream() throws IOException {
            return s.getInputStream();
        }

        @Override
        public OutputStream getOutputStream() throws IOException {
            return s.getOutputStream();
        }

        @Override
        public void close() throws IOException {
            s.close();
        }
    };
}
 
Example 5
Source File: Monitor.java    From CameraViewer with Apache License 2.0 6 votes vote down vote up
public void startMonitor(com.gl.cameraviewer.monitor.IMonitor iMonitor) {
    Data data = new Data(mCamId, mPassword);//请求启动摄像头
    mRunning = true;
    try {
        byte[] bytes = data.toBytes();
        Socket socket = new Socket(mIP, mPort);
        OutputStream mOutputStream = socket.getOutputStream();
        mOutputStream.write(bytes);
        mOutputStream.flush();
        receiveCommand(socket.getInputStream(), iMonitor);
        Log.i(TAG, "接收线程已停止");
    } catch (IOException e) {
        e.printStackTrace();
        stopMonitor();
        iMonitor.connectFailed();
    }
}
 
Example 6
Source File: ShutdownInput.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void test(Socket s1, Socket s2, String mesg) throws Exception {
    OutputStream os = s1.getOutputStream();
    os.write("This is a message".getBytes("US-ASCII"));

    InputStream in = s2.getInputStream();
    s2.shutdownInput();

    if (in.available() != 0) {
        failed = true;
        System.out.println(mesg + ":" + s2 + " in.available() should be 0, " +
                           "but returns "+ in.available());
    }

    byte[] ba = new byte[2];
    if (in.read() != -1 ||
        in.read(ba) != -1 ||
        in.read(ba, 0, ba.length) != -1) {

        failed = true;
        System.out.append(mesg + ":" + s2 + " in.read() should be -1");
    }
}
 
Example 7
Source File: RtmpPing.java    From android-netdiag with MIT License 6 votes vote down vote up
private int handshake(Socket socket) throws IOException {
    OutputStream out = socket.getOutputStream();
    InputStream input = socket.getInputStream();

    byte[] c0_c1 = c0_c1();

    send_c0_c1(out, c0_c1);

    byte[] s0_s1 = new byte[RTMP_SIG_SIZE + 1];

    boolean b = verify_s0_s1(input, s0_s1);
    if (!b) {
        return ServerVersionError;
    }

    send_c2(out, s0_s1, 1);


    b = verify_s2(input, s0_s1, c0_c1);
    if (!b) {
        return ServerSignatureError;
    }
    return 0;
}
 
Example 8
Source File: BridgeManager.java    From raccoon4 with Apache License 2.0 5 votes vote down vote up
public List<Device> listDevices() {
	Socket socket = null;
	try {
		socket = createSocket();
		InputStream in = socket.getInputStream();
		OutputStream out = socket.getOutputStream();
		ProtocolSupport.send("host:devices", in, out);
		byte[] buf = new byte[4];
		int len = Integer.parseInt(new String(buf, 0, 4), 16);
		buf = new byte[len];
		in.read(buf);
		String[] lines = new String(buf, 0, len).split("\n");
		ArrayList<Device> devices = new ArrayList<Device>(lines.length);
		for (String line : lines) {
			String[] parts = line.split("\t");
			if (parts.length > 1) {
				devices.add(new Device(parts[0]));
			}
		}
		socket.close();
		return devices;
	}
	catch (Exception e) {
		if (socket != null) {
			try {
				socket.close();
			}
			catch (IOException e1) {
			}
		}
		e.printStackTrace();
		return new ArrayList<Device>(0);
	}
}
 
Example 9
Source File: S7Client.java    From mokka7 with Eclipse Public License 1.0 5 votes vote down vote up
private void openTcpConnect(int timeout) throws S7Exception {
    try {
        tcpSocket = new Socket();
        tcpSocket.connect(new InetSocketAddress(config.getHost(), config.getPort()), timeout);
        tcpSocket.setTcpNoDelay(true);
        tcpSocket.setSoTimeout(recvTimeout);
        inStream = new BufferedInputStream(tcpSocket.getInputStream());
        outStream = new BufferedOutputStream(tcpSocket.getOutputStream());
    } catch (IOException e) {
        throw buildException(TCP_CONNECTION_FAILED, e);
    }
}
 
Example 10
Source File: HttpProxy.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void send200(Socket clientSocket) throws IOException {
    OutputStream out = clientSocket.getOutputStream();
    PrintWriter pout = new PrintWriter(out);

    pout.println("HTTP/1.1 200 OK");
    pout.println();
    pout.flush();
}
 
Example 11
Source File: StompExample.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static void sendFrame(Socket socket, String data) throws Exception {
   byte[] bytes = data.getBytes(StandardCharsets.UTF_8);
   OutputStream outputStream = socket.getOutputStream();
   for (int i = 0; i < bytes.length; i++) {
      outputStream.write(bytes[i]);
   }
   outputStream.flush();
}
 
Example 12
Source File: InvalidLdapFilters.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void doServerSide() throws Exception {
    ServerSocket serverSock = new ServerSocket(serverPort);

    // signal client, it's ready to accecpt connection
    serverPort = serverSock.getLocalPort();
    serverReady = true;

    // accept a connection
    Socket socket = serverSock.accept();
    System.out.println("Server: Connection accepted");

    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();

    // read the bindRequest
    while (is.read() != -1) {
        // ignore
        is.skip(is.available());
        break;
    }

    byte[] bindResponse = {0x30, 0x0C, 0x02, 0x01, 0x01, 0x61, 0x07, 0x0A,
                           0x01, 0x00, 0x04, 0x00, 0x04, 0x00};
    // write bindResponse
    os.write(bindResponse);
    os.flush();

    // ignore any more request.
    while (is.read() != -1) {
        // ignore
        is.skip(is.available());
    }

    is.close();
    os.close();
    socket.close();
    serverSock.close();
}
 
Example 13
Source File: SocketTextStreamFunctionTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void testSocketSourceSimpleOutput() throws Exception {
	ServerSocket server = new ServerSocket(0);
	Socket channel = null;

	try {
		SocketTextStreamFunction source = new SocketTextStreamFunction(LOCALHOST, server.getLocalPort(), "\n", 0);

		SocketSourceThread runner = new SocketSourceThread(source, "test1", "check");
		runner.start();

		channel = server.accept();
		OutputStreamWriter writer = new OutputStreamWriter(channel.getOutputStream());

		writer.write("test1\n");
		writer.write("check\n");
		writer.flush();
		runner.waitForNumElements(2);

		runner.cancel();
		runner.interrupt();

		runner.waitUntilDone();

		channel.close();
	}
	finally {
		if (channel != null) {
			IOUtils.closeQuietly(channel);
		}
		IOUtils.closeQuietly(server);
	}
}
 
Example 14
Source File: SocketConnection.java    From jsmpp with Apache License 2.0 4 votes vote down vote up
public SocketConnection(Socket socket) throws IOException {
    this.socket = socket;
    this.in = new StrictBufferedInputStream(socket.getInputStream(), 65536);// 64 KB buffer
    this.out = socket.getOutputStream();
}
 
Example 15
Source File: Client.java    From DeepDriver with Apache License 2.0 4 votes vote down vote up
public void run() throws  Exception {
		System.out.println("employeeNumber= "
                + joe .getEmployeeNumber());
System.out.println("employeeName= "
                + joe .getEmployeeName());

Socket socketConnection = new Socket("127.0.0.1", 11111);


ObjectOutputStream clientOutputStream = new
ObjectOutputStream(socketConnection.getOutputStream());
ObjectInputStream clientInputStream = new 
ObjectInputStream(socketConnection.getInputStream());

clientOutputStream.writeObject(joe);
clientOutputStream.flush();

Employee joe2 = (Employee)clientInputStream.readObject();
System.out.println(joe);
System.out.println(joe2);
System.out.println("employeeNumber= "
                + joe2 .getEmployeeNumber());
System.out.println("employeeName= "
                + joe2 .getEmployeeName());
joe2.setEmployeeName("aaaa");
joe2.setEmployeeNumber(1);
clientOutputStream.writeObject(joe2);
clientOutputStream.flush();

joe2 = (Employee)clientInputStream.readObject();
System.out.println(joe);
System.out.println(joe2);
System.out.println("employeeNumber= "
                + joe2 .getEmployeeNumber());
System.out.println("employeeName= "
                + joe2 .getEmployeeName());
joe2.setEmployeeName("bbbb");
joe2.setEmployeeNumber(2);
clientOutputStream.writeObject(joe2);
clientOutputStream.flush();

clientOutputStream.close();
clientInputStream.close();
	}
 
Example 16
Source File: NonAutoClose.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
void doServerSide() throws Exception {
    if (VERBOSE) {
        System.out.println("Starting server");
    }

    /*
     * Setup the SSL stuff
     */
    SSLSocketFactory sslsf =
         (SSLSocketFactory) SSLSocketFactory.getDefault();

    ServerSocket serverSocket = new ServerSocket(SERVER_PORT);

    SERVER_PORT = serverSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    Socket plainSocket = serverSocket.accept();
    InputStream is = plainSocket.getInputStream();
    OutputStream os = plainSocket.getOutputStream();

    expectValue(is.read(), PLAIN_CLIENT_VAL, "Server");

    os.write(PLAIN_SERVER_VAL);
    os.flush();

    for (int i = 1; i <= NUM_ITERATIONS; i++) {
        if (VERBOSE) {
            System.out.println("=================================");
            System.out.println("Server Iteration #" + i);
        }

        SSLSocket ssls = (SSLSocket) sslsf.createSocket(plainSocket,
            SERVER_NAME, plainSocket.getPort(), false);

        ssls.setUseClientMode(false);
        InputStream sslis = ssls.getInputStream();
        OutputStream sslos = ssls.getOutputStream();

        expectValue(sslis.read(), TLS_CLIENT_VAL, "Server");

        sslos.write(TLS_SERVER_VAL);
        sslos.flush();

        sslis.close();
        sslos.close();
        ssls.close();

        if (VERBOSE) {
            System.out.println("TLS socket is closed");
        }
    }

    expectValue(is.read(), PLAIN_CLIENT_VAL, "Server");

    os.write(PLAIN_SERVER_VAL);
    os.flush();

    is.close();
    os.close();
    plainSocket.close();

    if (VERBOSE) {
        System.out.println("Server plain socket is closed");
    }
}
 
Example 17
Source File: TestCometProcessor.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Tests if the Comet connection is closed if the Tomcat connector is
 * stopped.
 */
@Test
public void testCometConnectorStop() throws Exception {
    Assume.assumeTrue(
            "This test is skipped, because this connector does not support Comet.",
            isCometSupported());

    // Setup Tomcat instance
    SimpleCometServlet servlet = new SimpleCometServlet();
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "comet", servlet);
    root.addServletMapping("/", "comet");
    tomcat.start();

    // Create connection to Comet servlet
    final Socket socket =
        SocketFactory.getDefault().createSocket("localhost", getPort());
    socket.setSoTimeout(10000);

    final OutputStream os = socket.getOutputStream();
    String requestLine = "POST http://localhost:" + getPort() +
            "/ HTTP/1.1\r\n";
    os.write(requestLine.getBytes());
    os.write("transfer-encoding: chunked\r\n".getBytes());
    os.write("\r\n".getBytes());

    PingWriterThread writeThread = new PingWriterThread(100, os);
    writeThread.start();

    InputStream is = socket.getInputStream();
    ResponseReaderThread readThread = new ResponseReaderThread(is);
    readThread.start();

    // Allow the first couple of PING messages to be written
    Thread.sleep(3000);

    tomcat.getConnector().stop();

    // Wait for the read and write threads to stop
    readThread.join(5000);
    writeThread.join(5000);

    // Destroy the connector once the executor has sent the end event
    tomcat.getConnector().destroy();

    String[] response = readThread.getResponse().split("\r\n");
    String lastMessage = "";
    String lastResponseLine = "";
    for (int i = response.length; --i >= 0;) {
        lastMessage = response[i];
        if (lastMessage.startsWith("Client:")) {
            break;
        }
    }
    for (int i = response.length; --i >= 0;) {
        lastResponseLine = response[i];
        if (lastResponseLine.length() > 0) {
            break;
        }
    }
    StringBuilder status = new StringBuilder();
    // Expected, but is not 100% reliable:
    // WriteThread exception: java.net.SocketException
    // ReaderThread exception: null
    // Last message: [Client: END]
    // Last response line: [0] (empty chunk)
    // Last comet event: [END]
    // END event occurred: [true]
    status.append("Status:");
    status.append("\nWriterThread exception: " + writeThread.getException());
    status.append("\nReaderThread exception: " + readThread.getException());
    status.append("\nLast message: [" + lastMessage + "]");
    status.append("\nLast response line: [" + lastResponseLine + "]");
    status.append("\nLast comet event: [" + servlet.getLastEvent() + "]");
    status.append("\nEND event occurred: [" + servlet.getEndEventOccurred() + "]");
    if (writeThread.getException() == null
            || !lastMessage.contains("Client: END")
            || !EventType.END.equals(servlet.getLastEvent())) {
        log.error(status);
    } else {
        log.info(status);
    }
    assertTrue("Comet END event not received", servlet.getEndEventOccurred());
    assertTrue("Comet END event not last event received",
            EventType.END.equals(servlet.getLastEvent()));
}
 
Example 18
Source File: Pinger.java    From AndriodVideoCache with Apache License 2.0 4 votes vote down vote up
void responseToPing(Socket socket) throws IOException {
    OutputStream out = socket.getOutputStream();
    out.write("HTTP/1.1 200 OK\n\n".getBytes());
    out.write(PING_RESPONSE.getBytes());
}
 
Example 19
Source File: StreamServer.java    From Amphitheatre with Apache License 2.0 4 votes vote down vote up
/**
 * Sends given response to the socket.
 */
private void sendResponse(Socket socket, String status, String mime, Properties header, StreamSource data )
{
	try
	{
		if ( status == null )
			throw new Error( "sendResponse(): Status can't be null." );

		OutputStream out = socket.getOutputStream();
		PrintWriter pw = new PrintWriter( out );
		pw.print("HTTP/1.0 " + status + " \r\n");


		if ( mime != null )
			pw.print("Content-Type: " + mime + "\r\n");

		if ( header == null || header.getProperty( "Date" ) == null )
			pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n");

		if ( header != null )
		{
			Enumeration<Object> e = header.keys();
			while ( e.hasMoreElements())
			{
				String key = (String)e.nextElement();
				String value = header.getProperty( key );
				pw.print( key + ": " + value + "\r\n");
			}
		}

		pw.print("\r\n");
		pw.flush();


		if ( data != null )
		{
			//long pending = data.available();      // This is to support partial sends, see serveFile()
			data.open();
			byte[] buff = new byte[bufsize];
			int read = 0;
			while ((read = data.read(buff))>0){
				//if(SolidStreamer.LOG)Log.d("Streamer", "Read: "+ read +", pending: "+ data.available());
				out.write( buff, 0, read );
			}
		}
		out.flush();
		out.close();
		if ( data != null )
			data.close();

	}
	catch(IOException ioe) {
		// Couldn't write? No can do.
		try { socket.close(); } catch( Throwable t ) {}
	}
}
 
Example 20
Source File: NetUtils.java    From hadoop with Apache License 2.0 2 votes vote down vote up
/**
 * Returns OutputStream for the socket. If the socket has an associated
 * SocketChannel then it returns a 
 * {@link SocketOutputStream} with the given timeout. If the socket does not
 * have a channel, {@link Socket#getOutputStream()} is returned. In the later
 * case, the timeout argument is ignored and the write will wait until 
 * data is available.<br><br>
 * 
 * Any socket created using socket factories returned by {@link NetUtils},
 * must use this interface instead of {@link Socket#getOutputStream()}.
 * 
 * @see Socket#getChannel()
 * 
 * @param socket
 * @param timeout timeout in milliseconds. This may not always apply. zero
 *        for waiting as long as necessary.
 * @return OutputStream for writing to the socket.
 * @throws IOException   
 */
public static OutputStream getOutputStream(Socket socket, long timeout) 
                                           throws IOException {
  return (socket.getChannel() == null) ? 
          socket.getOutputStream() : new SocketOutputStream(socket, timeout);            
}