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

The following examples show how to use java.net.Socket#getInputStream() . 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: ShutdownInput.java    From openjdk-jdk8u-backup 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 2
Source File: ShutdownInput.java    From hottub 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 3
Source File: LFSByteArray.java    From LFS with Apache License 2.0 6 votes vote down vote up
public void readStream(Socket socket, IStreamParse streamParse) throws IOException
{
	ensureCapacity(messageLength, false);
	InputStream in = socket.getInputStream();
	int bytesAvalibale = 0;
	while (position < messageLength) {
		bytesAvalibale = in.read(buf, position, messageLength - position);
		if (bytesAvalibale > 0) {
			if (null != streamParse) {
				streamParse.parseData(buf, bytesAvalibale, position, messageLength);
			}
			position += bytesAvalibale;
		}
		else if (bytesAvalibale < 0) {
			throw new IOException("Broken Pipe");
		}
	}
	initVars(false);
	totalTime = System.currentTimeMillis() - totalTime;
}
 
Example 4
Source File: VirtualApkCheckUtil.java    From EasyProtector with Apache License 2.0 6 votes vote down vote up
private ReadThread(String secret, Socket socket, VirtualCheckCallback callback) {
    InputStream inputStream = null;
    try {
        inputStream = socket.getInputStream();
        byte buffer[] = new byte[1024 * 4];
        int temp = 0;
        while ((temp = inputStream.read(buffer)) != -1) {
            String result = new String(buffer, 0, temp);
            if (result.contains(secret) && callback != null)
                callback.findSuspect();
        }
        inputStream.close();
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: LocalServerManager.java    From AppOpsX with MIT License 6 votes vote down vote up
private ClientSession createSession() throws IOException {
  if(isRunning()){
    return mSession;
  }
  Socket socket = new Socket("127.0.0.1", SConfig.getPort());
  socket.setSoTimeout(1000 * 30);
  OutputStream os = socket.getOutputStream();
  InputStream is = socket.getInputStream();
  String token = SConfig.getLocalToken();
  if (TextUtils.isEmpty(token)) {
    throw new RuntimeException("token is null !");
  }
  OpsDataTransfer transfer = new OpsDataTransfer(os, is, false);
  transfer.shakehands(token, false);
  return new ClientSession(transfer);
}
 
Example 6
Source File: LdapTimeoutTest.java    From openjdk-jdk8u 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 7
Source File: TConnection.java    From iec61850bean with Apache License 2.0 6 votes vote down vote up
TConnection(
    Socket socket,
    int maxTPduSizeParam,
    int messageTimeout,
    int messageFragmentTimeout,
    ServerThread serverThread)
    throws IOException {
  if (maxTPduSizeParam < 7 || maxTPduSizeParam > 16) {
    throw new RuntimeException("maxTPduSizeParam is incorrect");
  }
  this.socket = socket;
  os = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
  is = new DataInputStream(new BufferedInputStream(socket.getInputStream()));

  synchronized (connectionCounter) {
    srcRef = connectionCounter.getAndIncrement();
  }

  this.messageTimeout = messageTimeout;
  this.messageFragmentTimeout = messageFragmentTimeout;
  this.maxTPduSizeParam = maxTPduSizeParam;
  maxTPduSize = ClientTSap.getMaxTPDUSize(maxTPduSizeParam);

  this.serverThread = serverThread;
}
 
Example 8
Source File: Client111.java    From MiniWeChat-Server with MIT License 5 votes vote down vote up
public void link() throws UnknownHostException, IOException {
	socket = new Socket(host, port);
	inputStream = socket.getInputStream();
	outputStream = socket.getOutputStream();
	
	byte[] byteArray = new byte[100];
	while (true) {
		inputStream.read(byteArray);
		System.out.println(byteArray);
	}
}
 
Example 9
Source File: HttpProxy.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void processRequest(Socket clientSocket) throws Exception {
    MessageHeader mheader = new MessageHeader(clientSocket.getInputStream());
    String statusLine = mheader.getValue(0);

    if (!statusLine.startsWith("CONNECT")) {
        out.println("proxy server: processes only "
                          + "CONNECT method requests, recieved: "
                          + statusLine);
        return;
    }

    // retrieve the host and port info from the status-line
    InetSocketAddress serverAddr = getConnectInfo(statusLine);

    //open socket to the server
    try (Socket serverSocket = new Socket(serverAddr.getAddress(),
                                          serverAddr.getPort())) {
        Forwarder clientFW = new Forwarder(clientSocket.getInputStream(),
                                           serverSocket.getOutputStream());
        Thread clientForwarderThread = new Thread(clientFW, "ClientForwarder");
        clientForwarderThread.start();
        send200(clientSocket);
        Forwarder serverFW = new Forwarder(serverSocket.getInputStream(),
                                           clientSocket.getOutputStream());
        serverFW.run();
        clientForwarderThread.join();
    }
}
 
Example 10
Source File: SimpleLoggerServer.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
public ConnectionHandler(Socket input) {
    try {
        this.inputStream = new ObjectInputStream(new BufferedInputStream(input.getInputStream()));
    } catch (IOException e) {
        logger.error("", e);
    }
}
 
Example 11
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 12
Source File: HttpReceiveSocket.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Layer on top of a pre-existing Socket object, and use specified
 * input and output streams.
 * @param socket the pre-existing socket to use
 * @param in the InputStream to use for this socket (can be null)
 * @param out the OutputStream to use for this socket (can be null)
 */
public HttpReceiveSocket(Socket socket, InputStream in, OutputStream out)
    throws IOException
{
    super(socket, in, out);

    this.in = new HttpInputStream(in != null ? in :
                                               socket.getInputStream());
    this.out = (out != null ? out :
                socket.getOutputStream());
}
 
Example 13
Source File: HttpProxy.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void simpleDataExchange(Socket s1, Socket s2) throws Exception {
    try (final InputStream i1 = s1.getInputStream();
         final InputStream i2 = s2.getInputStream();
         final OutputStream o1 = s1.getOutputStream();
         final OutputStream o2 = s2.getOutputStream()) {
        startSimpleWriter("simpleWriter1", o1, 100);
        startSimpleWriter("simpleWriter2", o2, 200);
        simpleRead(i2, 100);
        simpleRead(i1, 200);
    }
}
 
Example 14
Source File: TCPClient.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
public static void main(String argv[]) throws Exception {
	String sentence = "hello";
	String modifiedSentence;
	//BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
	Socket clientSocket = new Socket("localhost", 6789);
	DataOutputStream outToServer = new DataOutputStream(
			clientSocket.getOutputStream());
	BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
			clientSocket.getInputStream()));
	//sentence = inFromUser.readLine();
	outToServer.writeBytes(sentence + '\n');
	modifiedSentence = inFromServer.readLine();
	System.out.println("FROM SERVER: " + modifiedSentence);
	clientSocket.close();
}
 
Example 15
Source File: VisionDriver.java    From SoftwarePilot with MIT License 5 votes vote down vote up
void readFullPic() throws IOException {
    ServerSocket ss = new ServerSocket(12013);
    System.out.println("Server: Waiting for Connection");
    Socket s = ss.accept();
    System.out.println("Server: Connection Reached");

    String line, message = "";
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

    System.out.println("Reading Metadata");
    while((line = br.readLine())!= null) {
        if(!line.equals("over")) {
            System.out.println(line);
            message += line+"\n";
        } else {
            System.out.println("OVER");
            break;
        }
    }
    System.out.println("Metadata Done:");
    System.out.println(message);
    s.close();

    s = ss.accept();
    DataInputStream dIn = new DataInputStream(s.getInputStream());
    byte[] ret = new byte[0];

    int length = dIn.readInt();
    System.out.println("Receiving "+length+" Bytes");
    if(length > 0) {
        ret = new byte[length];
        dIn.readFully(ret, 0, ret.length);
    }

    System.out.println(message);
    s.close();
    ss.close();
    writeByte(ret);
    writeYaml(message);
}
 
Example 16
Source File: NonAutoClose.java    From jdk8u_jdk 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
private void doSimpleCometTest(String initParam) throws Exception {
    Assume.assumeTrue(
            "This test is skipped, because this connector does not support Comet.",
            isCometSupported());

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Wrapper w = Tomcat.addServlet(root, "comet", new SimpleCometServlet());
    if (initParam != null) {
        w.addInitParameter(initParam, "true");
    }
    root.addServletMapping("/", "comet");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    root.getPipeline().addValve(alv);

    tomcat.start();

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

    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(4, os);
    writeThread.start();

    socket.setSoTimeout(25000);
    InputStream is = socket.getInputStream();
    ResponseReaderThread readThread = new ResponseReaderThread(is);
    readThread.start();
    readThread.join();
    os.close();
    is.close();

    String[] response = readThread.getResponse().split("\r\n");
    if (initParam == null) {
        // Normal response expected
        // Validate response
        assertEquals("HTTP/1.1 200 OK", response[0]);
        assertEquals("Server: Apache-Coyote/1.1", response[1]);
        assertTrue(response[2].startsWith("Set-Cookie: JSESSIONID="));
        assertEquals("Content-Type: text/plain;charset=ISO-8859-1", response[3]);
        assertEquals("Transfer-Encoding: chunked", response[4]);
        assertTrue(response[5].startsWith("Date: "));
        assertEquals("", response[6]);
        assertEquals("7", response[7]);
        assertEquals("BEGIN", response[8]);
        assertEquals("", response[9]);
        assertEquals("17", response[10]);
        assertEquals("Client: READ: 4 bytes", response[11]);
        assertEquals("", response[12]);
        assertEquals("17", response[13]);
        assertEquals("Client: READ: 4 bytes", response[14]);
        assertEquals("", response[15]);
        assertEquals("17", response[16]);
        assertEquals("Client: READ: 4 bytes", response[17]);
        assertEquals("", response[18]);
        assertEquals("17", response[19]);
        assertEquals("Client: READ: 4 bytes", response[20]);
        assertEquals("", response[21]);
        assertEquals("d", response[22]);
        assertEquals("Client: END", response[23]);
        assertEquals("", response[24]);
        assertEquals("0", response[25]);
        // Expect 26 lines
        assertEquals(26, response.length);
    } else {
        // Failure expected only expected for the fail on begin
        // Failure at any later stage and the response headers (including
        // the 200 response code will already have been sent to the client
        if (SimpleCometServlet.FAIL_ON_BEGIN.equals(initParam)) {
            assertEquals("HTTP/1.1 500 Internal Server Error", response[0]);
            alv.validateAccessLog(1, 500, 0, 1000);
        } else {
            assertEquals("HTTP/1.1 200 OK", response[0]);
            alv.validateAccessLog(1, 200, 0, 5000);
        }

    }
}
 
Example 18
Source File: TestFtpClientNameListWithNull.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public void handleClient(Socket client) throws IOException {
    boolean done = false;
    String str;

    client.setSoTimeout(2000);
    BufferedReader in = new BufferedReader(new InputStreamReader(client.
            getInputStream()));
    PrintWriter out = new PrintWriter(client.getOutputStream(), true);
    out.println("220 FTP serverSocket is ready.");
    while (!done) {
        try {
            str = in.readLine();
        } catch (SocketException e) {
            done = true;
            continue;
        }
        String cmd = str.substring(0, str.indexOf(" ") > 0 ?
                str.indexOf(" ") : str.length());
        String args = (cmd.equals(str)) ?
                "" : str.substring(str.indexOf(" "));
        switch (cmd) {
            case "QUIT":
                out.println("221 Goodbye.");
                out.flush();
                done = true;
                break;
            case "EPSV":
                if ("all".equalsIgnoreCase(args)) {
                    out.println("200 EPSV ALL command successful.");
                    continue;
                }
                out.println("229 Entering Extended Passive Mode " +
                        "(|||" + getPort() + "|)");
                break;
            case "NLST":
                if (args.trim().length() != 0) {
                    commandHasArgs = true;
                }
                out.println("200 Command okay.");
                break;
            default:
                out.println("500 unsupported command: " + str);
        }
    }
}
 
Example 19
Source File: TcpHandler.java    From Azzet with Open Software License 3.0 3 votes vote down vote up
/**
 * Instantiates a new TcpHandler.
 * 
 * @param server
 *        The server that created this handler.
 * @param socket
 *        The socket to handle requests from.
 * @throws IOException
 *         An error occurred creating the sockets I/O stream.
 */
public TcpHandler( TcpServer server, Socket socket ) throws IOException
{
	this.assetServer = server;
	this.socket = socket;
	this.socketInput = new DataInputStream( new BufferedInputStream( socket.getInputStream() ) );
	this.socketOutput = new DataOutputStream( new BufferedOutputStream( socket.getOutputStream() ) );
}
 
Example 20
Source File: SocketReader.java    From binnavi with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new socket reader object.
 *
 * @param socket The socket to read from.
 *
 * @throws IOException Thrown if the input stream of the socket can't be opened.
 */
public SocketReader(final Socket socket) throws IOException {
  Preconditions.checkNotNull(socket, "IE00745: Socket can not be null");
  m_InputStream = new BufferedInputStream(socket.getInputStream());
}