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:com.opengamma.livedata.client.CogdaLiveDataClient.java

@Override
public void start() {
    if (_socket != null) {
        throw new IllegalStateException("Socket is currently established.");
    }/*from  w  ww. j a va2s.  co  m*/
    InetAddress serverAddress = null;
    try {
        serverAddress = InetAddress.getByName(getServerName());
    } catch (UnknownHostException ex) {
        s_logger.error("Illegal host name: " + getServerName(), ex);
        throw new IllegalArgumentException("Cannot identify host " + getServerName());
    }
    try {
        Socket socket = new Socket(serverAddress, getServerPort());
        InputStream is = socket.getInputStream();
        OutputStream os = socket.getOutputStream();
        _messageSender = new ByteArrayFudgeMessageSender(new OutputStreamByteArrayMessageSender(os));

        login(is);

        InputStreamFudgeMessageDispatcher messageDispatcher = new InputStreamFudgeMessageDispatcher(is, this);
        Thread t = new Thread(messageDispatcher, "CogdaLiveDataClient Dispatch Thread");
        t.setDaemon(true);
        t.start();
        _socketReadThread = t;

        _socket = socket;
    } catch (IOException ioe) {
        s_logger.error("Unable to establish connection to" + getServerName() + ":" + getServerPort(), ioe);
        throw new OpenGammaRuntimeException(
                "Unable to establish connection to" + getServerName() + ":" + getServerPort());
    }

}

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

@Test
public void testConnect() throws IOException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.replay(sockMock);//from   w  w  w . j a  v  a  2  s.c  o m

    shoutcast.start(sockMock);

    String expected = "password1\n";
    expected += "content-type: " + shoutcast.getStreamInfo(Sourcer.CONTENT_TYPE) + "\n";
    expected += "icy-genre: " + shoutcast.getStreamInfo(Sourcer.ICY_GENRE) + "\n";
    expected += "icy-pub: " + shoutcast.getStreamInfo(Sourcer.ICY_PUB) + "\n";
    expected += "icy-name: " + shoutcast.getStreamInfo(Sourcer.ICY_NAME) + "\n";
    expected += "icy-url: " + shoutcast.getStreamInfo(Sourcer.ICY_URL) + "\n";
    expected += "icy-br: " + String.valueOf(bitrate) + "\n\n";

    String http = new String(out.toByteArray());
    Assert.assertEquals(expected, http);
}

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

@Test
public void testUpdateMetadata() throws IOException, URISyntaxException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("HTTP OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.expect(sockMock.isConnected()).andReturn(true);
    EasyMock.replay(sockMock);//from  w w  w  .j a va 2s . c  om

    shoutcast.start(sockMock);

    HttpUriRequest request = shoutcast.getUpdateMetadataRequest("song", "artist", "album");
    Assert.assertEquals(shoutcast.getHost(), request.getURI().getHost());
    Assert.assertEquals(shoutcast.getPort(), request.getURI().getPort());

    HashMap<String, String> paramsMap = getParams(request);
    Assert.assertEquals("album song artist", paramsMap.get("song"));
}

From source file:com.kyne.webby.rtk.modules.BukkitInterface.java

@SuppressWarnings("unchecked")
private <T> T sendRequestAndCastResponse(final RequestType type, final Map<String, Object> params,
        final Class<T> responseDataType) throws IOException {
    Socket clientSocket = null;
    ObjectOutputStream serverOutputStream = null;
    ObjectInputStream serverInputStream = null;

    final WebbyLocalData request = new WebbyLocalData(type, params);
    try {/*from ww  w. ja v  a  2  s.  co m*/
        clientSocket = new Socket("localhost", this.localPort);
        serverOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
        serverInputStream = new ObjectInputStream(clientSocket.getInputStream());
        serverOutputStream.writeObject(request);
        final WebbyLocalData response = (WebbyLocalData) serverInputStream.readObject();
        if (this.lastKnownStatus != ServerStatus.RESTARTING) {
            this.lastKnownStatus = ServerStatus.ON;
        }
        return (T) response.getRequestParams().get("DATA");
    } catch (final Exception e) {
        this.lastKnownStatus = ServerStatus.OFF;
        LogHelper.debug("Bukkit is offline or restarting");
        return null;
    } finally {
        IOUtils.closeQuietly(serverInputStream);
        IOUtils.closeQuietly(serverOutputStream);
        IOUtils.closeQuietly(clientSocket);
    }
}

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

@Test
public void testConnectSuccess() throws IOException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("HTTP OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.expect(sockMock.isConnected()).andReturn(true);
    EasyMock.replay(sockMock);// w  w  w.  jav  a2 s.  c  o  m

    boolean started = icecast.start(sockMock);

    Assert.assertTrue(started);
    Assert.assertTrue(icecast.isStarted());
}

From source file:ca.uhn.hunit.example.MllpHl7v2MessageSwapper.java

@Override
public void run() {
    Socket socket = null;

    try {//www  .j a  v  a2 s .c  o  m
        if (myPrintOutput) {
            System.out.println("Opening server socket on port " + 10201);
        }

        ServerSocket serverSocket = new ServerSocket(10201);

        socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        inputStream = new BufferedInputStream(inputStream);

        MinLLPReader minLLPReader = new MinLLPReader(inputStream);

        Socket outSocket = null;

        if (myPrintOutput) {
            System.out.println("Accepting connection from " + socket.getInetAddress().getHostAddress());
        }

        for (int i = 0; i < myIterations; i++) {
            String messageText;

            do {
                messageText = minLLPReader.getMessage();
                Thread.sleep(250);
            } while (messageText == null);

            if (myPrintOutput) {
                System.out.println("Received message:\r\n" + messageText + "\r\n");
            }

            MSH inboundHeader = (MSH) myParser.parse(messageText).get("MSH");
            String controlId = inboundHeader.getMessageControlID().encode();
            if (StringUtils.isNotBlank(controlId) && myControlIdsToIgnore.indexOf(controlId) > -1) {
                Message replyAck = DefaultApplication.makeACK(inboundHeader);
                new MinLLPWriter(socket.getOutputStream()).writeMessage(myParser.encode(replyAck));
            } else {
                System.out.println("Ignoring message with control ID " + controlId);
            }

            for (Map.Entry<String, String> next : mySubstitutions.entrySet()) {
                messageText = messageText.replace(next.getKey(), next.getValue());
            }

            if ((outSocket != null) && myAlwaysCreateNewOutboundConnection) {
                outSocket.close();
                outSocket = null;
            }

            if (outSocket == null) {
                if (myPrintOutput) {
                    System.out.println("Opening outbound connection to port " + 10200);
                }

                outSocket = new Socket();
                outSocket.connect(new InetSocketAddress("localhost", 10200));
            }

            if (myPrintOutput) {
                System.out.println("Sending message from port " + outSocket.getLocalPort() + ":\r\n"
                        + messageText + "\r\n");
            }

            new MinLLPWriter(outSocket.getOutputStream()).writeMessage(messageText);
            new MinLLPReader(outSocket.getInputStream()).getMessage();
        }

        serverSocket.close();
        socket.close();

        myStopped = true;

    } catch (Exception e) {
        myStopped = true;
        e.printStackTrace();
    }
}

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

@Test
public void testUpdateMetadata() throws IOException, URISyntaxException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("HTTP OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.expect(sockMock.isConnected()).andReturn(true);
    EasyMock.replay(sockMock);/* www  . java  2s  .  c  o  m*/

    icecast.start(sockMock);

    HttpUriRequest request = icecast.getUpdateMetadataRequest("song", "artist", "album");
    Assert.assertEquals(icecast.getHost(), request.getURI().getHost());
    Assert.assertEquals(icecast.getPort(), request.getURI().getPort());

    HashMap<String, String> paramsMap = getParams(request);
    Assert.assertEquals(icecast.getPath(), paramsMap.get("mount"));
    Assert.assertEquals("updinfo", paramsMap.get("mode"));
    Assert.assertEquals("album song artist", paramsMap.get("song"));
}

From source file:jhttpp2.Jhttpp2HTTPSession.java

public Jhttpp2HTTPSession(Jhttpp2Server server, Socket client) {
    try {//w  w  w.  j av  a  2 s . c o  m
        in = new Jhttpp2ClientInputStream(server, this, client.getInputStream());// ,true);
        out = new BufferedOutputStream(client.getOutputStream());
        this.server = server;
        this.client = client;
    } catch (IOException e_io) {
        try {
            client.close();
        } catch (IOException e_io2) {
            log.debug("Error while closing client (kinda expected)" + e_io);
        }
        log.warn("Error while creating IO-Streams: ", e_io);
        return;
    }
    start();
}

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

@Test
public void testConnect() throws IOException {
    Socket sockMock = EasyMock.createNiceMock(Socket.class);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayInputStream in = new ByteArrayInputStream(new String("HTTP OK").getBytes());

    EasyMock.expect(sockMock.getOutputStream()).andReturn(out);
    EasyMock.expect(sockMock.getInputStream()).andReturn(in);
    EasyMock.replay(sockMock);/*w w  w.  j ava  2 s  . c om*/

    icecast.start(sockMock);

    String expected = "SOURCE /stream1 HTTP/1.0\n";
    expected += "Authorization: Basic dXNlcm5hbWUxOnBhc3N3b3JkMQ==\n";
    expected += "User-Agent: " + Sourcer.USER_AGENT + "\n";
    expected += "icy-notice1: " + Sourcer.USER_AGENT + "\n";
    expected += "content-type: " + icecast.getStreamInfo(Sourcer.CONTENT_TYPE) + "\n";
    expected += "icy-genre: " + icecast.getStreamInfo(Sourcer.ICY_GENRE) + "\n";
    expected += "icy-pub: " + icecast.getStreamInfo(Sourcer.ICY_PUB) + "\n";
    expected += "icy-name: " + icecast.getStreamInfo(Sourcer.ICY_NAME) + "\n";
    expected += "icy-url: " + icecast.getStreamInfo(Sourcer.ICY_URL) + "\n";
    expected += "icy-br: " + String.valueOf(bitrate) + "\n\n";

    String http = new String(out.toByteArray());
    Assert.assertEquals(expected, http);
}

From source file:fm.last.android.player.StreamProxy.java

private HttpRequest readRequest(Socket client) {
    HttpRequest request = null;/*  w ww  . j a  va  2 s. com*/
    InputStream is;
    String firstLine;
    String range = null;
    String ua = null;
    try {
        is = client.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8192);
        firstLine = reader.readLine();

        String line = null;

        do {
            line = reader.readLine();
            if (line != null && line.toLowerCase().startsWith("range: ")) {
                range = line.substring(7);
            }
            if (line != null && line.toLowerCase().startsWith("user-agent: ")) {
                ua = line.substring(12);
            }
        } while (line != null && !"".equals(line) && reader.ready());
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error parsing request", e);
        return request;
    }

    if (firstLine == null) {
        Log.i(LOG_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(LOG_TAG, uri);
    String realUri = uri.substring(1);
    Log.d(LOG_TAG, realUri);
    request = new BasicHttpRequest(method, realUri, new ProtocolVersion("HTTP", 1, 1));
    if (range != null)
        request.addHeader("Range", range);
    if (ua != null)
        request.addHeader("User-Agent", ua);
    return request;
}