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:org.mycard.net.network.HttpConnection.java

/***
 * Opens the connection to a http server
 *
 * @return the opened low level connection
 * @throws IOException if the connection fails for any reason.
 *//*from w w w  .  jav a  2  s  . c o m*/
@Override
AndroidHttpClientConnection openConnection(Request req) throws IOException {

    // Update the certificate info (connection not secure - set to null)
    //EventHandler eventHandler = req.getEventHandler();
    //mCertificate = null;
    //eventHandler.certificate(mCertificate);

    AndroidHttpClientConnection conn = new AndroidHttpClientConnection();
    BasicHttpParams params = new BasicHttpParams();
    Socket sock = new Socket();
    sock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort()), 20 * 1000);
    params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192);

    conn.bind(sock, params);
    return conn;
}

From source file:br.com.autonomiccs.autonomic.plugin.common.utils.HostUtils.java

private boolean isHostReachableOnPort(String addr, int openPort, int timeOutMillis) {
    if (StringUtils.isBlank(addr)) {
        return false;
    }//from  w w  w .  j av  a  2  s.  c om
    try {
        try (Socket soc = new Socket()) {
            soc.connect(new InetSocketAddress(addr, openPort), timeOutMillis);
        }
        return true;
    } catch (IOException ex) {
        logger.debug(
                String.format("Error while checking if host[%s] on port [%d] is reacheable", addr, openPort),
                ex);
        return false;
    }
}

From source file:com.flipkart.phantom.thrift.impl.proxy.SocketObjectFactory.java

/**
 * Interface method implementation. Creates and returns a new {@link java.net.Socket}
 * @see org.apache.commons.pool.PoolableObjectFactory#makeObject()
 *///w w  w . ja v a 2s . co m
public Socket makeObject() throws Exception {
    Socket socket = new Socket();
    socket.setSoTimeout(this.getThriftProxy().getThriftTimeoutMillis());
    socket.connect(new InetSocketAddress(this.getThriftProxy().getThriftServer(),
            this.getThriftProxy().getThriftPort()));
    LOGGER.info("Creating a new socket for server : {} at port : {}", this.getThriftProxy().getThriftServer(),
            this.getThriftProxy().getThriftPort());
    return socket;
}

From source file:com.fuzhouxiu.coretransfer.net.core.TcpSocket.java

/** Creates a new UdpSocket */
public TcpSocket(IpAddress ipaddr, int port, String host) throws java.io.IOException {
    //      socket = new Socket(ipaddr.getInetAddress(), port); modified
    SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getSocketFactory();
    if (host == null)
        socket = new Socket();
    else/*  w w w.j a  v a 2s .  com*/
        socket = f.createSocket();
    if (lock)
        throw new java.io.IOException();
    lock = true;
    try {
        socket.connect(new InetSocketAddress(ipaddr.toString(), port),
                Thread.currentThread().getName().equals("main") ? 1000 : 10000);
    } catch (java.io.IOException e) {
        lock = false;
        throw e;
    }
    if (host != null) {
        HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
        SSLSession s = ((SSLSocket) socket).getSession();
        if (!hv.verify(host, s)) {
            lock = false;
            throw new java.io.IOException();
        }
    }
    lock = false;
}

From source file:at.bitfire.davdroid.webdav.TlsSniSocketFactoryTest.java

public void testCreateLayeredSocket() {
    try {//  w  ww .  jav  a 2  s. c om
        // connect plain socket first
        @Cleanup
        Socket plain = new Socket();
        plain.connect(sampleTlsEndpoint);
        assertTrue(plain.isConnected());

        // then create TLS socket on top of it and establish TLS Connection
        @Cleanup
        Socket socket = factory.createLayeredSocket(plain, sampleTlsEndpoint.getHostName(),
                sampleTlsEndpoint.getPort(), null);
        assertTrue(socket.isConnected());

    } catch (IOException e) {
        Log.e(TAG, "I/O exception", e);
        fail();
    }
}

From source file:nl.phanos.liteliveresultsclient.LoginHandler.java

public static boolean isReachable() {
    // Any Open port on other machine
    // openPort =  22 - ssh, 80 or 443 - webserver, 25 - mailserver etc.
    try {/*from  w ww.j a  va2s.c  o  m*/
        try (Socket soc = new Socket()) {
            soc.connect(new InetSocketAddress("www.atletiek.nu", 80), 2000);
        }
        return true;
    } catch (IOException ex) {
        return false;
    }
}

From source file:dk.dma.ais.bus.provider.TcpClientProvider.java

@Override
public void run() {
    setNotConnected();/*from  w  w  w  . jav a 2s.c  o  m*/
    while (true) {
        socket = new Socket();

        // Get next host and port
        selectHost();
        String host = hostnames.get(currentHost);
        int port = ports.get(currentHost);

        // Connect
        try {
            InetSocketAddress address = new InetSocketAddress(host, port);
            LOG.info("Connecting to " + host + ":" + port + " ...");
            socket.connect(address);
            socket.setKeepAlive(true);
            if (timeout > 0) {
                socket.setSoTimeout(timeout * 1000);
            }

            setConnected();

            // Start client
            readClient = new TcpReadClient(this, this, socket, clientConf);
            readClient.start();
            // Wait for client to loose connection
            readClient.join();
            readClient = null;
        } catch (IOException e) {
            LOG.info(getName() + ": connection error: " + e.getMessage());
        } catch (InterruptedException e) {
            readClient.cancel();
            break;
        }

        setNotConnected();

        try {
            LOG.info("Waiting to reconnect");
            Thread.sleep(reconnectInterval * 1000);
        } catch (InterruptedException e) {
            break;
        }

    }

    setStopped();
}

From source file:com.chess.genesis.net.SocketClient.java

public synchronized void disconnect() {
    try {/*w ww .  ja  v a 2  s . com*/
        if (socket != null)
            socket.close();
        socket = new Socket();
        loginHash = null;
        isLoggedin = false;
    } catch (final IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.googlecode.android_scripting.jsonrpc.JsonRpcServerTest.java

public void testInvalidHandshake() throws IOException, JSONException, InterruptedException {
    JsonRpcServer server = new JsonRpcServer(null, "foo");
    InetSocketAddress address = server.startLocal(0);
    Socket client = new Socket();
    client.connect(address);/*  w  ww  . j a va 2s  . c o  m*/
    PrintStream out = new PrintStream(client.getOutputStream());
    out.println(buildRequest(0, "_authenticate", Lists.newArrayList("bar")));
    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    JSONObject response = new JSONObject(in.readLine());
    Object error = response.get("error");
    assertTrue(JSONObject.NULL != error);
    while (!out.checkError()) {
        out.println(buildRequest(0, "makeToast", Lists.newArrayList("baz")));
    }
    client.close();
    // Further connections should fail;
    client = new Socket();
    try {
        client.connect(address);
        fail();
    } catch (IOException e) {
    }
}

From source file:at.alladin.rmbt.android.util.CheckIpTask.java

@Override
protected JSONArray doInBackground(final Void... params) {
    needsRetry = false;// w w w . j a va2 s  .  c  o  m
    serverConn = new ControlServerConnection(activity);

    try {
        Socket s = new Socket();
        InetSocketAddress addr = new InetSocketAddress(
                ConfigHelper.getCachedControlServerNameIpv4(activity.getApplicationContext()),
                ConfigHelper.getControlServerPort(activity.getApplicationContext()));
        s.connect(addr, 5000);

        privateIpv4 = s.getLocalAddress();
        s.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        Socket s = new Socket();
        InetSocketAddress addr = new InetSocketAddress(
                ConfigHelper.getCachedControlServerNameIpv6(activity.getApplicationContext()),
                ConfigHelper.getControlServerPort(activity.getApplicationContext()));
        s.connect(addr, 5000);

        privateIpv6 = s.getLocalAddress();
        s.close();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        needsRetry = ConfigHelper.isRetryRequiredOnIpv6SocketTimeout(activity);
    } catch (Exception e) {
        needsRetry = false;
        e.printStackTrace();
    }

    newsList = new JSONArray();

    if (privateIpv4 != null) {
        JSONArray response = serverConn.requestIp(false);
        if (response != null && response.length() >= 1) {
            newsList.put(response.opt(0));
        }
    } else {
        Log.d(DEBUG_TAG, "no private ipv4 found");
    }

    if (privateIpv6 != null) {
        JSONArray response = serverConn.requestIp(true);
        if (response != null && response.length() >= 1) {
            newsList.put(response.opt(0));
        }
    } else {
        Log.d(DEBUG_TAG, "no private ipv6 found");
    }

    return newsList;
}