Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:SocketApplet.java

/** Initialize the GUI nicely. */
public void init() {
    Label aLabel;//  w w  w. jav a  2s  .c o  m

    setLayout(new GridBagLayout());
    int LOGO_COL = 1;
    int LABEL_COL = 2;
    int TEXT_COL = 3;
    int BUTTON_COL = 1;
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 100.0;
    gbc.weighty = 100.0;

    gbc.gridx = LABEL_COL;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.EAST;
    add(aLabel = new Label("Name:", Label.CENTER), gbc);
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridx = TEXT_COL;
    gbc.gridy = 0;
    add(nameTF = new TextField(10), gbc);

    gbc.gridx = LABEL_COL;
    gbc.gridy = 1;
    gbc.anchor = GridBagConstraints.EAST;
    add(aLabel = new Label("Password:", Label.CENTER), gbc);
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridx = TEXT_COL;
    gbc.gridy = 1;
    add(passTF = new TextField(10), gbc);
    passTF.setEchoChar('*');

    gbc.gridx = LABEL_COL;
    gbc.gridy = 2;
    gbc.anchor = GridBagConstraints.EAST;
    add(aLabel = new Label("Domain:", Label.CENTER), gbc);
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.gridx = TEXT_COL;
    gbc.gridy = 2;
    add(domainTF = new TextField(10), gbc);
    sendButton = new Button("Send data");
    gbc.gridx = BUTTON_COL;
    gbc.gridy = 3;
    gbc.gridwidth = 3;
    add(sendButton, gbc);

    whence = getCodeBase();

    // Now the action begins...
    sendButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            String name = nameTF.getText();
            if (name.length() == 0) {
                showStatus("Name required");
                return;
            }
            String domain = domainTF.getText();
            if (domain.length() == 0) {
                showStatus("Domain required");
                return;
            }
            showStatus("Connecting to host " + whence.getHost() + " as " + nameTF.getText());

            try {
                Socket s = new Socket(getCodeBase().getHost(), 3333);
                PrintWriter pf = new PrintWriter(s.getOutputStream(), true);
                // send login name
                pf.println(nameTF.getText());
                // passwd
                pf.println(passTF.getText());
                // and domain
                pf.println(domainTF.getText());

                BufferedReader is = new BufferedReader(new InputStreamReader(s.getInputStream()));
                String response = is.readLine();
                showStatus(response);
            } catch (IOException e) {
                showStatus("ERROR: " + e.getMessage());
            }
        }
    });
}

From source file:com.hulaki.smtp.api.ApiClient.java

private String sendRequestToApiServer(ApiRequest request) {
    try {//  w w  w.j ava2  s  . c o  m
        Socket clientSocket = new Socket(this.apiServerHostname, this.apiServerPort);
        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());

        String requestString = request.toRequestString() + "\n";
        logger.trace(requestString);
        out.writeBytes(requestString);
        StringBuilder response = new StringBuilder();
        logger.trace(response.toString());

        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        clientSocket.close();
        return response.toString();
    } catch (ConnectException e) {
        throw new ApiException("SMTP mock not available at " + apiServerHostname + ":" + apiServerPort);
    } catch (IOException e) {
        throw new ApiException(e);
    }
}

From source file:edu.mit.scratch.ScratchCloudSession.java

public ScratchCloudSession(final ScratchSession session, final String cloudToken, final int projectID)
        throws ScratchProjectException {
    this.session = session;
    this.cloudToken = cloudToken; // if !work, md5 cloudToken
    this.projectID = projectID;
    this.hashToken = this.MD5(this.getCloudToken());

    Socket socket = null;
    PrintWriter out = null;/*from   ww  w  . ja  v a 2s  .  c o  m*/
    BufferedReader in = null;

    try {
        socket = new Socket(Scratch.CLOUD_SERVER, Scratch.CLOUD_PORT);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        this.socket = socket;
        this.out = out;
        this.in = in;

        this.thread = new Thread(() -> {
            while (ScratchCloudSession.this.running) {
                String line = "";
                try {
                    line = ScratchCloudSession.this.in.readLine();
                } catch (final IOException e) {
                    e.printStackTrace();
                }
                if (line != null)
                    if (!line.equals("null") && !line.equals("{}"))
                        ScratchCloudSession.this.handleLine(line);

            }
        });
        this.thread.start();

        this.handshake();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

}

From source file:org.apache.flume.instrumentation.zabbix.ZabbixSender.java

private void send(final String key, final String value) throws IOException {
    final StringBuilder message = new StringBuilder(head);
    // message.append(Base64.encode(key));
    message.append(base64Encode(key));/*from  www  . ja  va  2 s . c om*/
    message.append(middle);
    // message.append(Base64.encode(value == null ? "" : value));
    message.append(base64Encode(value == null ? "" : value));
    message.append(tail);

    logger.trace("sending " + message);

    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;

    for (Map.Entry<String, Integer> zabbixServer : zabbixServers.entrySet()) {

        try {

            zabbix = new Socket(zabbixServer.getKey(), zabbixServer.getValue());
            zabbix.setSoTimeout(TIMEOUT);

            out = new OutputStreamWriter(zabbix.getOutputStream());
            out.write(message.toString());
            out.flush();

            in = zabbix.getInputStream();
            final int read = in.read(response);
            logger.trace("received " + new String(response));
            if (read != 2 || response[0] != 'O' || response[1] != 'K') {
                logger.warn(
                        "received unexpected response '" + new String(response) + "' for key '" + key + "'");
            }
        } catch (Exception ex) {
            logger.warn("Error contacting Zabbix server " + zabbixServer.getKey() + "  on port "
                    + zabbixServer.getValue());
        }

        finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (zabbix != null) {
                zabbix.close();
            }

        }
    }
}

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

@Override
public void run() {
    try {/*w  w w. j ava 2s.co  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:br.com.i9torpedos.model.service.serverSocket.DSSocketSIM1.java

@Override
public void run() {

    try {/*w w  w.ja  v a  2s  .  c  o m*/
        while (true) {
            Socket socket = server.accept();
            log.info("Cliente conectado  " + socket.getInetAddress());

            try {

                PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
                printWriter.println(conectou);
                log.info("Sinal de autenticao enviado para o Cliente  " + new Date().toString());

                //Faz verificao no fluxo de entrada do Objeto
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());

                try {

                    //faz a leitura do Objeto de entrada
                    Object readObject = objectInputStream.readObject();

                    if (readObject instanceof SendSMSMessage) {

                        try {

                            SendSMSMessage smsMessage = (SendSMSMessage) readObject;

                            // Thread.sleep(random.nextInt(10000));

                            ponte.set(smsMessage);
                            Thread t = new Thread(new ConsumerSendSMSMessage(ponte),
                                    "PONTE_ASYNC_DSSOCKETSIM1");
                            t.start();

                            listaSMS.add(smsMessage);

                            objectInputStream.close();
                            socket.close();

                            if (listaSMS.size() > 0 && !listaSMS.isEmpty()) {

                                DServiceModem1 md1 = new DServiceModem1(listaSMS, 1000);
                                new Thread(md1, "MODEM 1").start();
                                listaSMS.clear();

                            }

                        } catch (InterruptedException ex) {
                            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }

                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }

            } catch (IOException ex) {
                Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    socket.close();
                } catch (IOException ex) {
                    Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            server.close();
        } catch (IOException ex) {
            Logger.getLogger(DSSocketSIM1.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:info.varden.irclinqed.dcc.FileSendThread.java

@Override
public void onIPSelected(String ipAddress) {
    try {/*ww w .  j av a 2 s  .  c  o  m*/
        if (!this.file.exists()) {
            return;
        }
        this.server = new ServerSocket(0);
        this.server.setSoTimeout(60000);
        DCCRequestPacket packet = null;
        String filename = this.file.getName();
        if (filename.split(" ").length > 1) {
            filename = "\"" + filename + "\"";
        }
        if (this.thread instanceof IRCThread) {
            packet = new DCCRequestPacket(this.il, (IRCThread) this.thread, this.target, DCCType.SEND, filename,
                    ipAddress, server.getLocalPort(), this.totalSize);
        } else if (this.thread instanceof DCCThread) {
            VirtualIRCThread thrd = new VirtualIRCThread(this.il, (DCCThread) this.thread);
            packet = new DCCRequestPacket(this.il, thrd, this.target, DCCType.SEND, filename, ipAddress,
                    server.getLocalPort(), this.totalSize);
        } else {
            this.server.close();
            return;
        }
        packet.send();
        if (this.cancel) {
            this.server.close();
            return;
        }
        this.message = "Waiting for connection...";
        Socket s = this.server.accept();
        this.overlay.unload();
        this.gfp = new GuiFileProgress(this.il, this);
        this.il.guiQueue.add(this.gfp);
        InputStream i = new FileInputStream(this.file);
        this.cos = new CountingOutputStream(s.getOutputStream());
        byte[] buff = new byte[1024];
        int k = -1;
        while ((k = i.read(buff)) > -1 && !this.cancel) {
            this.cos.write(buff, 0, k);
            s.getInputStream().read(new byte[4]);
        }
        s.shutdownInput();
        s.shutdownOutput();
        s.close();
        this.server.close();
        i.close();
        this.gfp.unload();
    } catch (SocketTimeoutException e) {
        this.overlay.unload();
        Util.extractUtil(this.thread).writeToChat(MessageType.DCC_ERROR, "File send timed out.");
    } catch (IOException e) {
        e.printStackTrace();
    }
    this.overlay.unload();
}

From source file:com.bmwcarit.barefoot.matcher.ServerTest.java

private void sendRequest(InetAddress host, int port, JSONArray samples)
        throws InterruptedException, IOException, JSONException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;

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

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

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

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

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

    MatcherKState state = new MatcherKState(new JSONObject(response),
            new MatcherFactory(ServerControl.getServer().getMap()));

    OutputFormatter output = new GeoJSONOutputFormatter();
    PrintWriter out = new PrintWriter(ServerTest.class.getResource("").getPath() + "ServerTest-matching.json");
    out.println(output.format(null, state));
    out.close();

    assertEquals(samples.length(), state.sequence().size());
}

From source file:org.apache.axis2.transport.mail.server.SMTPWorker.java

private void doWork(Socket socket, Storage st, ConfigurationContext configurationContext) {
    try {//from   ww  w  .  ja v  a  2  s  .c  om
        this.st = st;

        if (configurationContext == null) {
            actAsMailet = false;
        } else {
            this.configurationContext = configurationContext;
            actAsMailet = true;
        }

        // get the streams from the socket and save in instance variables.
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (IOException ex) {
        log.info(ex.getMessage());
    }
}

From source file:net.java.jless.tls.Record.java

/**
 * Set the connect cipher states to null and writeSeqNums to zero.  Create
 * new socket connection to server//www  .  j a  v a 2s . com
 */
public void setSocket(Socket s) throws TLSException {
    try {
        clientWriteCipherIsNull = true;
        serverWriteCipherIsNull = true;
        clientWriteSeqNum = 0;
        serverWriteSeqNum = 0;
        outs = new BufferedOutputStream(s.getOutputStream());
        ins = new BufferedInputStream(s.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
        throw new TLSException("Error in Record.reset(): " + e.getMessage());
    }
}