Example usage for java.net Socket Socket

List of usage examples for java.net Socket Socket

Introduction

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

Prototype

public Socket() 

Source Link

Document

Creates an unconnected Socket.

Usage

From source file:dk.dma.epd.common.prototype.sensor.nmea.NmeaTcpSensor.java

private void connect() throws IOException {
    try {//from   w  w  w . ja  v a 2s.c o  m
        clientSocket = new Socket();
        InetSocketAddress address = new InetSocketAddress(hostname, port);
        clientSocket.connect(address);
        clientSocket.setKeepAlive(true);
        clientSocket.setSoTimeout(TCP_READ_TIMEOUT);
        outputStream = clientSocket.getOutputStream();
        LOG.info("NMEA source connected " + hostname + ":" + port);
    } catch (UnknownHostException e) {
        LOG.error("Unknown host: " + hostname + ": " + e.getMessage());
        throw e;
    } catch (IOException e) {
        LOG.error("Could not connect to NMEA source: " + hostname + ": " + e.getMessage());
        throw e;
    }
}

From source file:net.ruthandtodd.gpssync.rkoauth.RunkeeperOAuthClient.java

private static int getEphemeralPort() throws IOException {
    Socket s = new Socket();
    s.bind(null);//  w  ww  .j  a v a 2  s  .  co  m
    try {
        return s.getLocalPort();
    } finally {
        s.close();
    }
}

From source file:net.oauth.client.httpclient4.OAuthSchemeTest.java

@Override
public void setUp() throws Exception {
    { // Get an ephemeral local port number:
        Socket s = new Socket();
        s.bind(null);/*  w ww . ja  v a2s  . co m*/
        port = s.getLocalPort();
        s.close();
    }
    server = new Server(port);
    Context servletContext = new Context(server, "/", Context.SESSIONS);
    servletContext.addServlet(new ServletHolder(new ProtectedResource()), "/Resource/*");
    server.start();
    context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTH_SCHEME_PREF, Arrays.asList(OAuthSchemeFactory.SCHEME_NAME));
    client = new DefaultHttpClient();
    client.getAuthSchemes().register(OAuthSchemeFactory.SCHEME_NAME, new OAuthSchemeFactory());
    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", port),
            new OAuthCredentials(ProtectedResource.ACCESSOR));
}

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

/**
 * Called automatically by after when used as a JUnit ExternalResource.
 * Stop is exposed here for manual use.//  w  w w. j a v  a2  s  .  c o  m
 */
public void stop() {
    if (!finished.getAndSet(true)) {
        //if the server hadn't already finished then connect to it here to unblock the last
        //socket.accept() call and allow the server to terminate cleanly
        Socket socket = new Socket();
        try {
            socket.connect(getSocketAddress());
        } catch (Exception e) {
            log.log(Level.SEVERE, "Exception when shutting down ", e);
        } finally {
            IOUtils.closeQuietly(socket);
        }
    }
    IOUtils.closeQuietly(serverSocket);
    try {
        //wait for the server thread to finish
        serverThread.join();
    } catch (InterruptedException e) {
        log.log(Level.SEVERE, SimpleHttpServer.class.getName() + " interrupted", e);
    }
}

From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java

public LumberjackClient(String keyStorePath, String server, int port, int timeout) throws IOException {
    this.server = server;
    this.port = port;

    try {/*from   w  w w. j  ava  2  s. c o  m*/
        if (keyStorePath == null) {
            throw new IOException("Key store not configured");
        }
        if (server == null) {
            throw new IOException("Server address not configured");
        }

        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keyStorePath), null);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(keyStore);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        SSLSocketFactory socketFactory = context.getSocketFactory();
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server), port), timeout);
        socket.setSoTimeout(timeout);
        sslSocket = (SSLSocket) socketFactory.createSocket(socket, server, port, true);
        sslSocket.setUseClientMode(true);
        sslSocket.startHandshake();

        output = new DataOutputStream(new BufferedOutputStream(sslSocket.getOutputStream()));
        input = new DataInputStream(sslSocket.getInputStream());

        logger.info("Connected to " + server + ":" + port);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.grinder.util.NetworkUtil.java

private static InetAddress getAddressWithSocket(String byConnecting, int port) {
    Socket s = null;//from   w w w.ja  va  2  s  .c om
    try {
        s = new Socket();
        SocketAddress addr = new InetSocketAddress(byConnecting, port);
        s.connect(addr, 2000); // 2 seconds timeout
        return s.getLocalAddress();
    } catch (Exception e) {
        return null;
    } finally {
        IOUtils.closeQuietly(s);
    }
}

From source file:de.quist.samy.remocon.RemoteSession.java

private String initialize() throws UnknownHostException, IOException {
    logger.debug("Creating socket for host " + host + " on port " + port);

    socket = new Socket();
    socket.connect(new InetSocketAddress(host, port), 5000);

    logger.debug("Socket successfully created and connected");
    InetAddress localAddress = socket.getLocalAddress();
    logger.debug("Local address is " + localAddress.getHostAddress());

    logger.debug("Sending registration message");
    writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    writer.append((char) 0x00);
    writeText(writer, APP_STRING);//w ww . j  ava  2  s  .  com
    writeText(writer, getRegistrationPayload(localAddress.getHostAddress()));
    writer.flush();

    InputStream in = socket.getInputStream();
    reader = new InputStreamReader(in);
    String result = readRegistrationReply(reader);
    //sendPart2();
    int i;
    while ((i = in.available()) > 0) {
        in.skip(i);
    }
    return result;
}

From source file:com.lithium.flow.vault.AgentVault.java

@Nullable
private String readAgent() {
    String agentPort = store.getValue("vault.agent.port");
    String agentPassword = store.getValue("vault.agent.password");
    if (agentPort == null || agentPassword == null) {
        return null;
    }/*from w  w  w  . j a  v a  2  s.c o m*/

    try {
        int port = Integer.parseInt(agentPort);
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress("localhost", port), 5000);

        @SuppressWarnings("unchecked")
        Map<String, String> map = mapper.readValue(socket.getInputStream(), Map.class);

        Store agentStore = new MemoryStore(map);
        Vault agentVault = new SecureVault(Configs.empty(), agentStore);
        agentVault.unlock(agentPassword);
        return agentVault.getValue("password");
    } catch (Exception e) {
        log.debug("failed to read from agent", e);
        return null;
    }
}

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

@Override
public boolean start() {
    return start(new Socket());
}