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:fitnesse.FitNesseExpediter.java

public FitNesseExpediter(Socket socket, FitNesseContext context, ExecutorService executorService,
        long requestParsingTimeLimit) throws IOException {
    this.context = context;
    this.socket = socket;
    this.executorService = executorService;
    input = socket.getInputStream();
    output = socket.getOutputStream();// w w w  . j  av  a  2s. co  m
    this.requestParsingTimeLimit = requestParsingTimeLimit;
}

From source file:opendial.modules.core.RemoteConnector.java

/**
 * Infinite loop that reads content from the server socket<ul>
 * <li>If the message type is INIT, adds the connection to the list 
 *     of remote connections//from   w  ww  .  jav  a  2 s.c o  m
 * <li>If the message type is XML, adds the new distributions to the dialogue
 *     state
 * <li>If the message type is STREAM, play the stream on the output mixer
 * <li>If the message type is CLOSE, removes the connections from the list
 * </ul>
 */
private void readContent() {
    while (true) {
        try {
            Socket connection = local.accept();
            InputStream in = connection.getInputStream();
            MessageType type = MessageType.values()[in.read()];
            byte[] message = IOUtils.toByteArray(in);
            if (type == MessageType.INIT) {
                String content = new String(message);
                String ip = content.split(":")[0];
                int port = Integer.parseInt(content.split(":")[1]);
                log.info("Connected to " + ip + ":" + port);
                system.displayComment("Connected to " + ip + ":" + port);
                system.getSettings().remoteConnections.put(ip, port);
                if (system.getSettings().showGUI) {
                    system.getModule(GUIFrame.class).enableSpeech(true);
                    system.getModule(GUIFrame.class).getMenu().update();
                }
            } else if (type == MessageType.XML) {
                String content = new String(message);
                Document doc = XMLUtils.loadXMLFromString(content);
                BNetwork nodes = XMLStateReader.getBayesianNetwork(XMLUtils.getMainNode(doc));
                skipNextTrigger = true;
                system.addContent(nodes);
            } else if (type == MessageType.MISC) {
                String content = new String(message);
                log.info("received message: " + content);
            } else if (type == MessageType.STREAM) {
                AudioUtils.playAudio(message, system.getSettings().outputMixer);
            } else if (type == MessageType.CLOSE) {
                String content = new String(message);
                log.info("Disconnecting from " + content);
                system.displayComment("Disconnecting from " + content);
                String ip = content.split(":")[0];
                system.getSettings().remoteConnections.remove(ip);
            }
            Thread.sleep(100);
        } catch (IOException | InterruptedException | ParserConfigurationException | SAXException
                | DialException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.openmrs.module.mirebalais.integration.MirthIT.java

private String listenForResults() throws IOException {

    ServerSocket listener = new ServerSocket(6660); // TODO: store this port in a global property?
    listener.setSoTimeout(20000); // don't wait more than 20 seconds for an incoming connection

    Socket mirthConnection = listener.accept();

    BufferedReader reader = new BufferedReader(new InputStreamReader(mirthConnection.getInputStream()));

    StringBuilder sb = new StringBuilder();
    String line;/*from   ww w.  j  a va  2  s .c o  m*/

    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    // TODO: need an acknowledgement?

    mirthConnection.close();
    listener.close();

    return sb.toString();
}

From source file:org.npr.android.test.HttpServer.java

private String readRequest(Socket client) {

    InputStream is;//from  www  .j  a  va2s  .c o  m
    String firstLine;
    try {
        is = client.getInputStream();
        // We really don't need 8k (default) buffer (it throws a warning)
        // 2k is big enough: http://www.boutell.com/newfaq/misc/urllength.html
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 2048);
        firstLine = reader.readLine();
    } catch (IOException e) {
        Log.e(TAG, "Error parsing request from client", e);
        return null;
    }

    try {
        StringTokenizer st = new StringTokenizer(firstLine);
        st.nextToken(); // Skip method
        return URLDecoder.decode(st.nextToken(), "x-www-form-urlencoded");
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}

From source file:de.kapsi.net.daap.bio.DaapConnectionBIO.java

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

    this.server = server;
    this.socket = socket;

    in = new BufferedInputStream(socket.getInputStream());
    out = socket.getOutputStream();/*from   w ww.  j a  v  a2  s .  c  om*/

    connected = true;
}

From source file:WebServer.java

/**
 * WebServer constructor.//from w w w  . j  av  a 2s  .com
 */
protected void start() {
    ServerSocket s;

    System.out.println("Webserver starting up on port 80");
    System.out.println("(press ctrl-c to exit)");
    try {
        // create the main server socket
        s = new ServerSocket(80);
    } catch (Exception e) {
        System.out.println("Error: " + e);
        return;
    }

    System.out.println("Waiting for connection");
    for (;;) {
        try {
            // wait for a connection
            Socket remote = s.accept();
            // remote is now the connected socket
            System.out.println("Connection, sending data.");
            BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
            PrintWriter out = new PrintWriter(remote.getOutputStream());

            // read the data sent. We basically ignore it,
            // stop reading once a blank line is hit. This
            // blank line signals the end of the client HTTP
            // headers.
            String str = ".";
            while (!str.equals(""))
                str = in.readLine();

            // Send the response
            // Send the headers
            out.println("HTTP/1.0 200 OK");
            out.println("Content-Type: text/html");
            out.println("Server: Bot");
            // this blank line signals the end of the headers
            out.println("");
            // Send the HTML page
            out.println("<H1>Welcome to the Ultra Mini-WebServer</H2>");
            out.flush();
            remote.close();
        } catch (Exception e) {
            System.out.println("Error: " + e);
        }
    }
}

From source file:com.oakesville.mythling.util.MediaStreamProxy.java

private HttpRequest readRequest(Socket client) throws IOException {
    HttpRequest request = null;/*  w  w w  .  jav a  2s . co  m*/
    InputStream is;
    String firstLine;
    is = client.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
    firstLine = reader.readLine();

    if (firstLine == null) {
        Log.i(TAG, "Proxy client closed connection without a request.");
        return request;
    }

    StringTokenizer st = new StringTokenizer(firstLine);
    String method = st.nextToken();
    String uri = st.nextToken();
    Log.d(TAG, uri);
    String realUri = uri.substring(1);
    Log.d(TAG, realUri);
    request = new BasicHttpRequest(method, realUri);
    return request;
}

From source file:ru.codemine.ccms.counters.kondor.KondorClient.java

private File ftpDownload(Shop shop) {
    String login = settingsService.getCountersKondorFtpLogin();
    String pass = settingsService.getCountersKondorFtpPassword();
    String ip = shop.getProvider().getIp();
    String tmpFileName = settingsService.getStorageRootPath()
            + DateTime.now().toString("YYYYMMdd-s" + shop.getId());
    try {/*from   w  ww.ja  va 2 s .c o  m*/
        log.debug("Starting ftp session...");

        Socket manageSocket = new Socket();
        manageSocket.connect(new InetSocketAddress(ip, 21), 3000);
        BufferedReader in = new BufferedReader(new InputStreamReader(manageSocket.getInputStream()));
        PrintWriter out = new PrintWriter(manageSocket.getOutputStream(), true);
        String ftpAnswer;

        ftpAnswer = in.readLine();
        log.debug("FTP greetings: " + ftpAnswer);

        out.println("USER " + login);
        ftpAnswer = in.readLine();
        log.debug("FTP USER command responce: " + ftpAnswer);

        out.println("PASS " + pass);
        String afterAuth = in.readLine();
        log.debug("FTP PASS command responce: " + afterAuth);

        out.println("PASV");
        String pasvResponce = in.readLine();
        log.debug("FTP: PASV command responce: " + pasvResponce);

        if (pasvResponce.startsWith("227 (")) {
            pasvResponce = pasvResponce.substring(5);
            List<String> parsedPasv = new ArrayList<>(Arrays.asList(pasvResponce.split(",")));
            String p4 = parsedPasv.get(4);
            String p5 = parsedPasv.get(5).replace(")", "");
            int port = Integer.parseInt(p4) * 256 + Integer.parseInt(p5);

            log.debug("FTP: Recieved port: " + port);

            Socket dataSocket = new Socket();
            dataSocket.connect(new InetSocketAddress(ip, port), 3000);
            InputStream dataIn = dataSocket.getInputStream();
            FileOutputStream dataOut = new FileOutputStream(tmpFileName);

            out.println("RETR total.dbf");
            ftpAnswer = in.readLine();
            log.debug("FTP RETR command responce: " + ftpAnswer);

            IOUtils.copy(dataIn, dataOut);

            dataOut.flush();
            dataOut.close();
            dataSocket.close();
        } else {
            if (afterAuth.startsWith("530")) {
                log.warn(
                        "     ?, : "
                                + shop.getName());

            } else {
                log.warn(
                        " ?     PASV, : "
                                + shop.getName());
            }

        }

        out.println("QUIT");
        ftpAnswer = in.readLine();
        log.debug("FTP QUIT command responce: " + ftpAnswer);

        manageSocket.close();
    } catch (Exception e) {
        log.warn(
                "?   ? ?   "
                        + shop.getName() + ",  : " + e.getMessage());
    }

    return new File(tmpFileName);
}

From source file:hd3gtv.as5kpc.protocol.ProtocolHandler.java

public ProtocolHandler(Socket socket) throws ParserConfigurationException, IOException {
    this.socket = socket;
    is = socket.getInputStream();
    os = socket.getOutputStream();// w w w.  ja  v  a  2s  .  c o m
}

From source file:gridool.util.xfer.RecievedFileWriter.java

public final void handleRequest(@Nonnull final SocketChannel inChannel, @Nonnull final Socket socket)
        throws IOException {
    final StopWatch sw = new StopWatch();
    if (!inChannel.isBlocking()) {
        inChannel.configureBlocking(true);
    }/*w  w w.j  av  a2 s . c o m*/

    InputStream in = socket.getInputStream();
    DataInputStream dis = new DataInputStream(in);

    String fname = IOUtils.readString(dis);
    String dirPath = IOUtils.readString(dis);
    long len = dis.readLong();
    boolean append = dis.readBoolean();
    boolean ackRequired = dis.readBoolean();
    boolean hasAdditionalHeader = dis.readBoolean();
    if (hasAdditionalHeader) {
        readAdditionalHeader(dis, fname, dirPath, len, append, ackRequired);
    }

    final File file;
    if (dirPath == null) {
        file = new File(baseDir, fname);
    } else {
        File dir = FileUtils.resolvePath(baseDir, dirPath);
        file = new File(dir, fname);
    }

    preFileAppend(file, append);
    final FileOutputStream dst = new FileOutputStream(file, append);
    final String fp = file.getAbsolutePath();
    final ReadWriteLock filelock = accquireLock(fp, locks);
    final FileChannel fileCh = dst.getChannel();
    final long startPos = file.length();
    try {
        NIOUtils.transferFully(inChannel, 0, len, fileCh); // REVIEWME really an atomic operation?
    } finally {
        IOUtils.closeQuietly(fileCh, dst);
        releaseLock(fp, filelock, locks);
        postFileAppend(file, startPos, len);
    }
    if (ackRequired) {
        OutputStream out = socket.getOutputStream();
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeLong(len);
        postAck(file, startPos, len);
    }

    if (LOG.isDebugEnabled()) {
        SocketAddress remoteAddr = socket.getRemoteSocketAddress();
        LOG.debug("Received a " + (append ? "part of file '" : "file '") + file.getAbsolutePath() + "' of "
                + len + " bytes from " + remoteAddr + " in " + sw.toString());
    }
}