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:com.alibaba.dragoon.common.protocol.transport.socket.SocketSessionImpl.java

public SocketSessionImpl(Socket socket, AtomicLong receivedBytes, AtomicLong receivedMessages,
        AtomicLong sentBytes, AtomicLong sentMessages) {
    super();//  w w w  .  j  a v a  2s.c  om
    this.socket = socket;
    state = State.Established;

    this.receivedBytes = receivedBytes;
    this.receivedMessages = receivedMessages;
    this.sentBytes = sentBytes;
    this.sentMessages = sentMessages;

    try {
        dataInput = new DataInputStream(socket.getInputStream());
        writer = new DataOutputStream(socket.getOutputStream());
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.kyne.webby.rtk.web.WebServer.java

/**
 * Read a print a static file (js, css, html or png).
 * @param path the path to the file//from  w  ww  . j a  v  a2  s  .  co  m
 * @param type the mimetype
 * @param jsStates some javascripts variables that may be initialized in the printed content. Null if not required.
 * @param clientSocket the client-side socket
 */
public void printStaticFile(final String path, final String type, final Socket clientSocket,
        final Map<String, String> jsStates) {
    try {
        final File htmlPage = new File(path);
        if (htmlPage.exists()) {
            final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
            out.writeBytes("HTTP/1.1 200 OK\r\n");
            out.writeBytes("Content-Type: " + type + "; charset=utf-8\r\n");
            out.writeBytes("Cache-Control: no-cache \r\n");
            out.writeBytes("Server: Bukkit Webby\r\n");
            out.writeBytes("Connection: Close\r\n\r\n");
            if (jsStates != null) {
                out.writeBytes("<script type='text/javascript'>");
                for (final String var : jsStates.keySet()) {
                    out.writeBytes("var " + var + " = '" + jsStates.get(var) + "';");
                }
                out.writeBytes("</script>");
            }
            if (!this.htmlCache.containsKey(path)) { //Pages are static, so we can "pre-read" them. Dynamic content will be rendered with javascript
                final FileInputStream fis = new FileInputStream(htmlPage);
                final byte fileContent[] = new byte[(int) htmlPage.length()];
                fis.read(fileContent);
                fis.close();
                this.htmlCache.put(path, fileContent);
            } else {
                LogHelper.debug("File will be added in Webby's cache");
            }
            out.write(this.htmlCache.get(path));
            out.flush();
            out.close();
        } else {
            LogHelper.warn("Requested file " + path + " can't be found");
        }
    } catch (final SocketException e) {
        /* Or not ! */
    } catch (final Exception e) {
        LogHelper.error(e.getMessage(), e);
    }
}

From source file:Network.CSMSHandler.java

@Override
public void update(Observable o, Object arg) {

    Socket objSocket = (Socket) arg;

    int intSeq = -1;

    try {//from  w  w w  .j av  a 2s .c om

        JSONParser jsonParser = new JSONParser();

        JSONObject objJSON = (JSONObject) jsonParser.parse(new InputStreamReader(objSocket.getInputStream()));

        int intTempSeq = Integer.parseInt(objJSON.get("id").toString());

        for (CSMS objSMS : CSMSManager.loadFromJson((JSONArray) objJSON.get("sms"))) {

            CSMSFactory.getSMSSender().sendSMS(objSMS);
        }

        intSeq = intTempSeq;

    } catch (Exception ex) {
        System.out.println(ex);
    } finally {
        try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()),
                StandardCharsets.US_ASCII.name())) {

            objWriter.write(intSeq + "");
            objWriter.flush();

        } catch (IOException ex) {
            System.out.println(ex);
        }
    }

}

From source file:Network.CEmailHandler.java

@Override
public void update(Observable o, Object arg) {

    Socket objSocket = (Socket) arg;

    int intSeq = -1;

    try {//from   w w w  . j  a  va  2s .com

        JSONParser jsonParser = new JSONParser();

        JSONObject objJSON = (JSONObject) jsonParser.parse(new InputStreamReader(objSocket.getInputStream()));

        int intTempSeq = Integer.parseInt(objJSON.get("id").toString());

        emailSender.getEmailsToBeSent((JSONArray) objJSON.get("messagesToBeSent"));
        emailSender.dispatchEmail();

        intSeq = intTempSeq;

    } catch (IOException | ParseException | NumberFormatException ex) {
        System.out.println(ex);
    } finally {
        try (Writer objWriter = Channels.newWriter(Channels.newChannel(objSocket.getOutputStream()),
                StandardCharsets.US_ASCII.name())) {

            objWriter.write(intSeq + "");
            objWriter.flush();

        } catch (IOException ex) {
            System.out.println(ex);
        }
    }

}

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

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {//w  w  w .j a v  a  2s.  c o  m
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + Main.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

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

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                Main.updateStatusText(solution + " submitted", Color.blue);
                Thread gc = new Thread(new Coins());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                Main.updateStatusText("Submission of " + solution + " failed, already exists!", Color.red);
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        } catch (IOException e) {
            e.printStackTrace();
            Main.updateStatusText("Submission of " + solution + " failed, connection failed!", Color.red);
        }
    }
    Thread gc = new Thread(new Coins());
    gc.start();
}

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

private void submit() {
    for (int i = 0; i < solved.size(); i++) {
        try {/*from   www.ja v  a2  s  .  c o  m*/
            Socket sock = new Socket(this.url, this.port);
            String result = new String();
            DataInputStream is = new DataInputStream(sock.getInputStream());
            DataOutputStream os = null;
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            solution = solved.get(i);
            hash = DigestUtils.sha512Hex(solution);

            String command = "{\"cmd\":\"check" + "\",\"winning_string\":\"" + solution
                    + "\",\"winning_hash\":\"" + hash + "\",\"addr\":\"" + MainView.getAddr() + "\"}";
            os = new DataOutputStream(sock.getOutputStream());
            os.write(command.getBytes());

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

            if (result.contains("\"success\": true")) {
                System.out.println("Result: Submitted");
                MainView.updateStatusText(solution + " submitted");
                Thread gc = new Thread(new CoinClass());
                gc.start();
            } else if (result.contains("\"success\": false")) {
                System.out.println("Result: Failed");
                MainView.updateStatusText("Submission of " + solution + " failed, already exists!");
            }
            is.close();
            os.close();
            os.flush();
            sock.close();
        } catch (UnknownHostException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        } catch (IOException e) {
            MainView.updateStatusText("Submission of " + solution + " failed, connection failed!");
        }
    }
    Thread gc = new Thread(new CoinClass());
    gc.start();
}

From source file:com.cloudant.tests.util.SimpleHttpServer.java

@Override
public void run() {
    try {/*from www  .j ava  2  s  .  c  o  m*/
        try {
            //create a dynamic socket, and allow only 1 connection
            serverSocket = ssf.createServerSocket(0, 1);
        } catch (SocketException e) {
            log.severe("Unable to open server socket");
            finished.set(true);
        }
        // Listening to the port
        while (!finished.get() && !Thread.currentThread().isInterrupted()) {
            Socket socket = null;
            InputStream is = null;
            OutputStream os = null;
            try {
                log.fine("Server waiting for connections");
                //release a permit as we are about to accept connections
                semaphore.release();

                //block for connections
                socket = serverSocket.accept();

                log.fine("Server accepted connection");

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

                //do something with the request and then go round the loop again
                serverAction(is, os);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(socket);
            }
        }
        log.fine("Server stopping");
    } catch (Exception e) {
        log.log(Level.SEVERE, SimpleHttpServer.class.getName() + " exception", e);
    } finally {
        semaphore.release();
    }
}

From source file:com.techcavern.pircbotz.PircBotZ.java

protected void changeSocket(Socket socket) throws IOException {
    this.socket = socket;
    this.inputReader = new BufferedReader(
            new InputStreamReader(socket.getInputStream(), configuration.getEncoding()));
    this.outputWriter = new OutputStreamWriter(socket.getOutputStream(), configuration.getEncoding());
}

From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java

public MatcherKState requestState(InetAddress host, int port, String id)
        throws JSONException, InterruptedException, IOException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;

    while (client == null || !client.isConnected()) {
        try {/*from  www.j a  v  a 2  s. c  o  m*/
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                logger.error(e.getMessage());
                client.close();
                throw new IOException();
            } else {
                trials -= 1;
            }
        }
    }

    JSONObject json = new JSONObject();
    json.put("id", id);

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(json.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);

    String response = reader.readLine();
    client.close();

    return new MatcherKState(new JSONObject(response), new MatcherFactory(TrackerControl.getServer().getMap()));
}

From source file:com.photon.maven.plugins.android.AbstractEmulatorMojo.java

/**
 * Sends a user command to the running emulator via its telnet interface.
 *
 * @param port The emulator's telnet port.
 * @param command The command to execute on the emulator's telnet interface.
 * @return Whether sending the command succeeded.
 *///from   www.  j a v a2s.c o m
private boolean sendEmulatorCommand(
        //final Launcher launcher, 
        //final PrintStream logger,
        final int port, final String command) {
    Callable<Boolean> task = new Callable<Boolean>() {
        public Boolean call() throws IOException {
            Socket socket = null;
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                socket = new Socket("127.0.0.1", port);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                if (in.readLine() == null) {
                    return false;
                }

                out.write(command);
                out.write("\r\n");
            } finally {
                try {
                    out.close();
                    in.close();
                    socket.close();
                } catch (Exception e) {
                    // Do nothing
                }
            }

            return true;
        }

        private static final long serialVersionUID = 1L;
    };

    boolean result = false;
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Boolean> future = executor.submit(task);
        result = future.get();
    } catch (Exception e) {
        getLog().error(String.format("Failed to execute emulator command '%s': %s", command, e));
    }

    return result;
}