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

The following are Jave code examples for showing how to use getInputStream() of the java.net.Socket class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: T0rlib4j   File: SocksProxyBase.java   Source Code and License Vote up 8 votes
protected void startSession() throws SocksException {
	try {
		if (chainProxy == null) {
			proxySocket = new Socket(proxyIP, proxyPort);
		} else if (proxyIP != null) {
			proxySocket = new SocksSocket(chainProxy, proxyIP, proxyPort);
		} else {
			proxySocket = new SocksSocket(chainProxy, proxyHost, proxyPort);
		}

		in = proxySocket.getInputStream();
		out = proxySocket.getOutputStream();
	} catch (final SocksException se) {
		throw se;
	} catch (final IOException io_ex) {
		throw new SocksException(SOCKS_PROXY_IO_ERROR, "" + io_ex);
	}
}
 
Example 2
Project: featurea   File: TcpSlave.java   Source Code and License Vote up 7 votes
TcpConnectionHandler(Socket socket) throws ModbusInitException {
    this.socket = socket;
    try {
        transport = new TestableTransport(socket.getInputStream(), socket.getOutputStream());
    } catch (IOException e) {
        throw new ModbusInitException(e);
    }
}
 
Example 3
Project: CodeU-ProjectGroup6   File: ClientConnectionSource.java   Source Code and License Vote up 6 votes
private static Connection fromSocket(final Socket socket) throws IOException {

    return new Connection() {

      @Override
      public InputStream in() throws IOException {
        return socket.getInputStream();
      }

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

      @Override
      public void close() throws IOException {
        socket.close();
      }
    };
  }
 
Example 4
Project: WholesomeChat   File: MainController.java   Source Code and License Vote up 6 votes
/** Create socket, and receiving thread */
public void InitSocket(String server, int port) throws IOException {
    socket = new Socket(server, port);
    outputStream = socket.getOutputStream();

    Thread receivingThread = new Thread() {
        @Override
        public void run() {
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null)
                    notifyObservers(line);
            } catch (IOException ex) {
                notifyObservers(ex);
            }
        }
    };
    receivingThread.start();
}
 
Example 5
Project: karate   File: MonitorThread.java   Source Code and License Vote up 6 votes
@Override
public void run() {
    logger.info("starting thread: {}", getName());
    Socket accept;
    try {
        accept = socket.accept();
        BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
        reader.readLine();
        logger.info("shutting down thread: {}", getName());
        stoppable.stop();
        accept.close();
        socket.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Project: vase   File: HttpPost.java   Source Code and License Vote up 6 votes
@Override
public void process(Config config, String stateLine, Socket socket) {
    this.mConfig = config;
    Message request = new Message();

    InputStream inputStream = null;
    OutputStream outputStream = null;
    Headers headers;
    try {
        inputStream = socket.getInputStream();
        outputStream = socket.getOutputStream();
        headers = HttpUtils.readHeaders(inputStream);
        request.reqHeaders = (Headers) headers.clone();
        headers = HttpUtils.filterHeaders(headers);
    } catch (Exception e) {
        IOUtils.closeStream(inputStream);
        IOUtils.closeStream(outputStream);
        return;
    }
    request.reqStateLine = stateLine;

    proxyHttpPost(stateLine, headers, inputStream, outputStream, request);
}
 
Example 7
Project: votifier2-java   File: Votifier2Test.java   Source Code and License Vote up 5 votes
@Test
public void testVoteSending() throws Exception {
    try {
        /* Open up connection to Votifier */
        Socket socket = new Socket("127.0.0.1", 8192);

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

        /* Read Votifier packet and grab challenge token */
        String in = new BufferedReader(new InputStreamReader(is)).readLine();
        String[] votifierIn = in.split(" ");
        Assert.assertEquals("Incorrect Votifier data!", 3, votifierIn.length);
        Assert.assertEquals("Votifier signature mismatch", "VOTIFIER", votifierIn[0]);
        String challengeToken = votifierIn[2];

        /* Create vote object */
        Votifier2.Vote vote = Votifier2.newVoteObject(TEST_VOTER_NAME, TEST_SERVICE_NAME);
        byte[] message = Votifier2.encodeMessage(vote, challengeToken, TEST_SERVER_KEY);

        /* Send vote object */
        os.write(message);
        os.flush();

        /* Read status */
        in = new BufferedReader(new InputStreamReader(is)).readLine();
        JSONObject result = new JSONObject(in);
        Assert.assertEquals("Votifier status was not 'ok'! Data: " + result, "ok", result.get("status"));

        /* Close connection */
        os.close();
        socket.close();
    } catch(SocketException e){
        /* Skip test */
        Assume.assumeNoException(e);
    }
}
 
Example 8
Project: jdk8u-jdk   File: InvalidLdapFilters.java   Source Code and License Vote up 5 votes
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 9
Project: accumulate   File: BinaryIn.java   Source Code and License Vote up 5 votes
/**
 * Create a binary input stream from a socket.
 */
public BinaryIn(Socket socket) {
    try {
        InputStream is = socket.getInputStream();
        in = new BufferedInputStream(is);
        fillBuffer();
    }
    catch (IOException ioe) {
        System.err.println("Could not open " + socket);
    }
}
 
Example 10
Project: open-rmbt   File: ClientHandler.java   Source Code and License Vote up 5 votes
/**
 * 
 * @param serverSocket
 * @param socket
 * @throws IOException
 */
public ClientHandler(ServerSocket serverSocket, Socket socket) throws IOException {
	this.serverSocket = serverSocket;
	this.socket = socket;
	this.in = new BufferedInputStream(socket.getInputStream());
	this.out = new FilterOutputStream(socket.getOutputStream());
	this.reader = new BufferedReader(new InputStreamReader(in));
	this.name = "[ClientHandler " + socket.getInetAddress().toString() + "]";
}
 
Example 11
Project: CloudDB   File: MessageHandler.java   Source Code and License Vote up 5 votes
public MessageHandler(Socket socket, Logger logger) throws IOException{
	this.input = socket.getInputStream();
	this.output = socket.getOutputStream();
	this.socket = socket;
	this.logger = logger;
}
 
Example 12
Project: LotusCloud   File: PacketClient.java   Source Code and License Vote up 5 votes
public static Packet request(String host, int port, Packet packet) {
    KeyPair keyPair = Crypter.generateKeyPair();

    try {
        Socket socket = new Socket(host, port);

        if (socket.isClosed()) {
            return new ErrorPacket("socket closed");
        }

        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

        out.writeObject(keyPair.getPublic());
        PublicKey publicKey = (PublicKey) in.readObject();

        SecretKey key = Crypter.generateEC(keyPair.getPrivate(), publicKey);

        out.writeObject(Crypter.encrypt(key, Crypter.toByteArray(packet)));
        out.flush();

        Packet response = (Packet) Crypter.toObject(Crypter.decrypt(key, (byte[]) in.readObject()));

        in.close();
        out.close();
        socket.close();

        return response;
    } catch (Exception ex) {
        return new ErrorPacket(ex.getMessage());
    }
}
 
Example 13
Project: hadoop   File: TestBlockReplacement.java   Source Code and License Vote up 5 votes
private boolean replaceBlock(
    ExtendedBlock block,
    DatanodeInfo source,
    DatanodeInfo sourceProxy,
    DatanodeInfo destination,
    StorageType targetStorageType) throws IOException, SocketException {
  Socket sock = new Socket();
  try {
    sock.connect(NetUtils.createSocketAddr(destination.getXferAddr()),
        HdfsServerConstants.READ_TIMEOUT);
    sock.setKeepAlive(true);
    // sendRequest
    DataOutputStream out = new DataOutputStream(sock.getOutputStream());
    new Sender(out).replaceBlock(block, targetStorageType,
        BlockTokenSecretManager.DUMMY_TOKEN, source.getDatanodeUuid(),
        sourceProxy);
    out.flush();
    // receiveResponse
    DataInputStream reply = new DataInputStream(sock.getInputStream());

    BlockOpResponseProto proto =
        BlockOpResponseProto.parseDelimitedFrom(reply);
    while (proto.getStatus() == Status.IN_PROGRESS) {
      proto = BlockOpResponseProto.parseDelimitedFrom(reply);
    }
    return proto.getStatus() == Status.SUCCESS;
  } finally {
    sock.close();
  }
}
 
Example 14
Project: TeamProject   File: ServerSideClientHandler.java   Source Code and License Vote up 5 votes
public ServerSideClientHandler(Socket clientSocket, Queue playerQueue) {
    if (clientSocket == null) {
        System.err.println("[ERROR] ServerSideClientHandler constructor: Client socket is null.");
        System.exit(1);
    }
    this.clientSocket = clientSocket;
    try {
        this.inputStream = new ObjectInputStream(clientSocket.getInputStream());
        this.outputStream = new ObjectOutputStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.err.println("[ERROR] ServerSideClientHandler constructor: Couldn't get input or output stream from socket.");
    }
    this.playerQueue = playerQueue;
}
 
Example 15
Project: IOTproject   File: Client.java   Source Code and License Vote up 4 votes
public void createConnection() throws UnknownHostException, IOException{
	
	Socket client = new Socket("127.0.0.1", 2222);
	BufferedInputStream stream = new BufferedInputStream(client.getInputStream());
}
 
Example 16
Project: monarch   File: HandShake.java   Source Code and License Vote up 4 votes
/**
 * HandShake Constructor used by server side connection
 */
public HandShake(Socket sock, int timeout, DistributedSystem sys, Version clientVersion,
    byte communicationMode) throws IOException, AuthenticationRequiredException {
  this.clientVersion = clientVersion;
  this.system = sys;
  // SocketChannel sc = sock.getChannel();
  /*
   * if (sc != null) { } else
   */ {
    int soTimeout = -1;
    try {
      soTimeout = sock.getSoTimeout();
      sock.setSoTimeout(timeout);
      InputStream is = sock.getInputStream();
      int valRead = is.read();
      // this.code = (byte)is.read();
      if (valRead == -1) {
        throw new EOFException(
            LocalizedStrings.HandShake_HANDSHAKE_EOF_REACHED_BEFORE_CLIENT_CODE_COULD_BE_READ
                .toLocalizedString());
      }
      this.code = (byte) valRead;
      if (this.code != REPLY_OK) {
        throw new IOException(
            LocalizedStrings.HandShake_HANDSHAKE_REPLY_CODE_IS_NOT_OK.toLocalizedString());
      }
      try {
        DataInputStream dis = new DataInputStream(is);
        DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
        this.clientReadTimeout = dis.readInt();
        if (clientVersion.compareTo(Version.CURRENT) < 0) {
          // versioned streams allow object serialization code to deal with older clients
          dis = new VersionedDataInputStream(dis, clientVersion);
          dos = new VersionedDataOutputStream(dos, clientVersion);
        }
        this.id = ClientProxyMembershipID.readCanonicalized(dis);
        // Note: credentials should always be the last piece in handshake for
        // Diffie-Hellman key exchange to work
        if (clientVersion.compareTo(Version.GFE_603) >= 0) {
          setOverrides(new byte[] {dis.readByte()});
        } else {
          setClientConflation(dis.readByte());
        }
        // Hitesh
        if (this.clientVersion.compareTo(Version.GFE_65) < 0
            || communicationMode == Acceptor.GATEWAY_TO_GATEWAY) {
          this.credentials = readCredentials(dis, dos, sys);
        } else {
          this.credentials = this.readCredential(dis, dos, sys);
        }
      } catch (IOException ioe) {
        this.code = -2;
        throw ioe;
      } catch (ClassNotFoundException cnfe) {
        this.code = -3;
        throw new IOException(
            LocalizedStrings.HandShake_CLIENTPROXYMEMBERSHIPID_CLASS_COULD_NOT_BE_FOUND_WHILE_DESERIALIZING_THE_OBJECT
                .toLocalizedString());
      }
    } finally {
      if (soTimeout != -1) {
        try {
          sock.setSoTimeout(soTimeout);
        } catch (IOException ignore) {
        }
      }
    }
  }
}
 
Example 17
Project: ditb   File: LCCHFileMoverClient.java   Source Code and License Vote up 4 votes
private void openSocket() throws UnknownHostException, IOException {
  sock = new Socket(ip, port);
  sockIn = sock.getInputStream();
  sockOut = sock.getOutputStream();
}
 
Example 18
Project: T0rlib4Android   File: TCPForwardServer.java   Source Code and License Vote up 4 votes
public void run() {
    InputStream clientIn;
    OutputStream clientOut;
    InputStream serverIn;
    OutputStream serverOut;
    try {
        // Connect to the destination server
        mServerSocket = new Socket(
                DESTINATION_HOST,
                DESTINATION_PORT);

        // Turn on keep-alive for both the sockets
        mServerSocket.setKeepAlive(true);
        mClientSocket.setKeepAlive(true);

        // Obtain client & server input & output streams
        clientIn = mClientSocket.getInputStream();
        clientOut = mClientSocket.getOutputStream();
        serverIn = mServerSocket.getInputStream();
        serverOut = mServerSocket.getOutputStream();
    } catch (IOException ioe) {
        System.err.println("Can not connect to " +
                DESTINATION_HOST + ":" +
                DESTINATION_PORT);
        connectionBroken();
        return;
    }

    // Start forwarding data between server and client
    mForwardingActive = true;
    ForwardThread clientForward =
            new ForwardThread(this, clientIn, serverOut);
    clientForward.start();
    ForwardThread serverForward =
            new ForwardThread(this, serverIn, clientOut);
    serverForward.start();

    System.out.println("TCP Forwarding " +
            mClientSocket.getInetAddress().getHostAddress() +
            ":" + mClientSocket.getPort() + " <--> " +
            mServerSocket.getInetAddress().getHostAddress() +
            ":" + mServerSocket.getPort() + " started.");
}
 
Example 19
Project: Virtual-IoT-Server   File: SmartLight.java   Source Code and License Vote up 4 votes
public static void main(String[] args) {
  try{

    //Declare/instantiate LED and light sensor

    Gpio led = new Gpio(4);
    Aio lightSensor = new Aio(0);

    led.dir(Dir.DIR_OUT);

    int on = 0;
    long lightValue = 0;
    String command = "";

    //Set up socket and reading capabilities

    Socket clientSocket = new Socket(args[0], Integer.parseInt(args[1]));
    BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

    //IoT Device supplies server ip and port and the name of the plugin

    out.println(args[2] + ":" + args[3] + "|LightSensorPlugin");

    System.out.println(args[2] + ":" + args[3] + "SmartLight");


    System.out.println("\033[1m\033[32mSuccessfully connected to server\033[0m");

    //Get server input and issue commands based on that input

    while(true){
      lightValue = lightSensor.read();

      command = in.readLine().trim().toLowerCase();

      if(command.length() > 0) System.out.println(command);

      if(command.equals("off")){
        on = -1;
        led.write(0);
      }
      else if(command.equals("on")){
        on = 1;
        led.write(1);
      }
      else if(command.equals("reset")) on = 0;

      if(lightValue < 300 && on != -1){
        led.write(1);
      }
      else if(on != 1){
        led.write(0);
      }

      wait1Msec(10);
    }
  }
  catch(Exception e){
    e.printStackTrace();
  }
}
 
Example 20
Project: open-rmbt   File: NdtTests.java   Source Code and License Vote up 4 votes
public Protocol(Socket ctlSocket) throws IOException
{
  _ctlin = ctlSocket.getInputStream();
  _ctlout = ctlSocket.getOutputStream();
}