Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

In this page you can find the example usage for java.net Socket getOutputStream.

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:net.wimpi.modbus.io.ModbusTCPTransport.java

/**
 * Prepares the input and output streams of this
 * <tt>ModbusTCPTransport</tt> instance based on the given
 * socket.//  ww  w .  j a  v  a  2  s .co  m
 *
 * @param socket the socket used for communications.
 * @throws IOException if an I/O related error occurs.
 */
private void prepareStreams(Socket socket) throws IOException {

    m_Input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    m_Output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
    m_ByteIn = new BytesInputStream(Modbus.MAX_MESSAGE_LENGTH);
}

From source file:com.clough.android.adbv.manager.ADBManager.java

/**
 * Waiting for a device to connect and connect with it's one of eligible 
 * android application for AndroidDBViewer to run.
 * @return IOManager instance configured for a android application
 * @throws IOException/*  ww w  .  jav  a2  s.  c o  m*/
 * @throws ADBManagerException 
 */
public IOManager makeConnection() throws IOException, ADBManagerException {

    // Placing adb executable files for the desktop application use
    placeRelevantAdb();

    // Trying to connect with android application again and agian 
    // when ever an attempt is fail
    while (true) {
        try {

            // Creating a socket with PC_PORT and trying to connect with an server socket.
            // Connecting can fails due the ports not being forwarded or due to the
            // server socket not being started yet.
            // To be able to detect the server socket as running, a device must connected to the PC
            // and ADBVApplication configured android app must run on the device.
            final Socket deviceSocket = new Socket("localhost", PC_PORT);

            // Requesting to connect
            new PrintWriter(deviceSocket.getOutputStream(), true)
                    .println(new Data(Data.CONNECTION_REQUEST, "", "").toJSON().toString());
            Data recivedData = new Data(new JSONObject(
                    new BufferedReader(new InputStreamReader(deviceSocket.getInputStream())).readLine()));
            if (recivedData.getStatus() == Data.CONNECTION_ACCEPTED) {

                // Adding a shudown hook to disconnect the adb connection and close the socket connection
                Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

                    @Override
                    public void run() {
                        killServer();
                        try {
                            deviceSocket.shutdownInput();
                            deviceSocket.shutdownOutput();
                            deviceSocket.close();
                        } catch (IOException ex) {
                        }
                    }
                }));

                // Returning an IOManager created for this connection
                return new IOManager(deviceSocket);
            }
        } catch (IOException ex) {
            prepareADB();
        } catch (NullPointerException ex) {
            prepareADB();
        } catch (JSONException ex) {
            prepareADB();
        }
    }
}

From source file:com.rabbitmq.client.impl.SocketFrameHandler.java

/**
 * @param socket the socket to use//from  www. j  a  v  a 2 s.c  o m
 */
public SocketFrameHandler(Socket socket) throws IOException {
    _socket = socket;

    _inputStream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    _outputStream = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

    this.socketFrameHandler = this;
}

From source file:com.jredrain.startup.Bootstrap.java

/**
 *
 * @throws Exception//from  w  w w . jav a 2s .  co  m
 */

private void shutdown() throws Exception {
    /**
     * connect to startup socket and send stop command
     */
    Socket socket = new Socket("localhost", RedrainProperties.getInt("redrain.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("[redrain]shutdown:{}" + reply);
    }
    br.close();
    is.close();
    pw.close();
    os.close();
    socket.close();
}

From source file:net.mohatu.bloocoin.miner.RegCustom.java

private void register() {
    try {//from w  w  w  .  j a  v  a2 s .  c o m
        String result = new String();
        Socket sock = new Socket(this.url, this.port);
        String command = "{\"cmd\":\"register" + "\",\"addr\":\"" + addr + "\",\"pwd\":\"" + key + "\"}";
        DataInputStream is = new DataInputStream(sock.getInputStream());
        DataOutputStream os = new DataOutputStream(sock.getOutputStream());
        os.write(command.getBytes());
        os.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            result += inputLine;
        }

        is.close();
        os.close();
        sock.close();
        System.out.println(result);
        if (result.contains("\"success\": true")) {
            System.out.println("Registration successful: " + addr);
            saveBloostamp();
        } else if (result.contains("\"success\": false")) {
            System.out.println("Result: Failed");
            JOptionPane.showMessageDialog(Main.scrollPane,
                    "Registration failed.\nCheck your network connection", "Registration Failed",
                    JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Clases.cCifrado.java

public String pedirClave(String dato) {

    String clave = "";
    Scanner sc = new Scanner(System.in);
    Socket socket;
    try {//from   w ww  .  j av  a 2s  .  c o  m
        String ipServidor = receptor;
        int pto = puerto;
        System.out.println("conectando con el servidor...");
        socket = new Socket(ipServidor, pto);
        Scanner entrada = new Scanner(socket.getInputStream());
        PrintStream salidaServer = new PrintStream(socket.getOutputStream());
        salidaServer.println(dato);
        clave = entrada.nextLine();
        System.out.println("Dato recibido: " + clave);
        socket.close();

    } catch (IOException ex) {
        System.err.println("Cliente> " + ex.getMessage());
    }
    return clave;
}

From source file:com.supernovapps.audio.jstreamsourcer.ShoutcastV1.java

public boolean start(Socket sock) {
    try {//  w  w w.  ja  v  a  2s.com
        this.sock = sock;
        sock.connect(new InetSocketAddress(host, port), 5000);
        sock.setSendBufferSize(64 * 1024);
        out = sock.getOutputStream();

        PrintWriter output = writeAuthentication();

        InputStreamReader isr = new InputStreamReader(sock.getInputStream());
        BufferedReader in = new BufferedReader(isr);
        String line = in.readLine();
        if (line == null || !line.contains("OK")) {
            if (listener != null) {
                listener.onError("Connection / Authentification error");
            }

            return false;
        }

        while (line != null && line.length() > 0) {
            line = in.readLine();
        }

        writeHeaders(output);
    } catch (Exception e) {
        e.printStackTrace();

        try {
            if (sock != null)
                sock.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        if (listener != null) {
            listener.onError("Connection / Authentification error");
        }

        return false;
    }
    started = true;

    if (listener != null) {
        listener.onConnected();
    }

    return true;
}

From source file:org.ardverk.daap.bio.DaapConnectionBIO.java

public DaapConnectionBIO(DaapServerBIO server, Socket socket) throws IOException {
    super(server);

    this.socket = socket;

    in = new BufferedInputStream(socket.getInputStream());
    out = socket.getOutputStream();

    running = true;//from   w  w  w .  ja  v a2  s.c o  m
}

From source file:haxball.networking.ConnectionHandler.java

public ConnectionHandler(@NonNull Socket socket, @NonNull Dimension fieldSize, @NonNull Goal goals[], byte id) {
    this.socket = socket;
    this.fieldSize = fieldSize;
    this.id = id;

    try {/* w ww .  j  av a2  s  . com*/
        in = socket.getInputStream();
        out = socket.getOutputStream();

        // send dimension size
        out.write(serializeDimension(getFieldSize()));
        out.flush();

        out.write(id);

        out.write(goals.length);
        for (Goal g : goals) {
            out.write(serializeGoal(g));
        }

        // read name from client
        byte b[] = new byte[in.read()];
        if (in.read(b) != b.length) {
            throw new IOException();
        }
        name = new String(b, StandardCharsets.UTF_8);
        System.out.println("Connected client " + getSocket() + " as name " + name);

        // create player
        player = new Player(getId(), getName(), fieldSize);
        player.position = new Vector2D(100, 100);
    } catch (Exception ioe) {
        ioe.printStackTrace();
        try {
            socket.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.mule.module.http.functional.listener.HttpListenerPersistentConnectionsTestCase.java

protected void assertConnectionClosesWithRequestConnectionCloseHeader(DynamicPort port, HttpVersion httpVersion)
        throws IOException, InterruptedException {
    Socket socket = new Socket("localhost", port.getNumber());
    sendRequest(socket, httpVersion);/* w  ww. jav a  2 s . c o m*/
    assertResponse(getResponse(socket), true);

    sendRequest(socket, httpVersion);
    assertResponse(getResponse(socket), true);

    PrintWriter writer = new PrintWriter(socket.getOutputStream());
    writer.println("GET / " + httpVersion);
    writer.println("Host: www.example.com");
    writer.println("Connection: close");
    writer.println("");
    writer.flush();
    assertResponse(getResponse(socket), true);

    sendRequest(socket, httpVersion);
    assertResponse(getResponse(socket), false);

    socket.close();
}