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.eclipse.ecf.internal.provider.filetransfer.httpclient4.ECFHttpClientSecureProtocolSocketFactory.java

public Socket createSocket(final HttpParams params) {
    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING,
            ECFHttpClientSecureProtocolSocketFactory.class, "createSocket"); //$NON-NLS-1$

    Socket socket = new Socket();
    fireEvent(socketConnectListener, new SocketCreatedEvent(source, socket));

    Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING,
            ECFHttpClientSecureProtocolSocketFactory.class, "socketCreated " + socket); //$NON-NLS-1$
    return socket;
}

From source file:com.clustercontrol.port.protocol.ReachAddressTCP.java

/**
 * ????????????/*from  w w w  . j a va 2 s.  co m*/
 * 
 * @param addressText
 * @return PORT
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        // Reachability ?? ICMP ??
        boolean retry = true;

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the port of " + address.getHostName() + "[" + address.getHostAddress()
                + "]:" + m_portNo + ".\n\n");

        // 
        Socket socket = null;

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                // ?
                socket = new Socket();
                InetSocketAddress isa = new InetSocketAddress(address, m_portNo);

                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                start = HinemosTime.currentTimeMillis();
                socket.connect(isa, m_timeout);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;
                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = ("Response Time < 1ms");
                }
                retry = false;
                isReachable = true;
            } catch (BindException e) {
                result = (e.getMessage() + "[BindException]");
                retry = true;
                isReachable = false;
            } catch (ConnectException e) {
                result = (e.getMessage() + "[ConnectException]");
                retry = false;
                isReachable = false;
            } catch (NoRouteToHostException e) {
                result = (e.getMessage() + "[NoRouteToHostException]");
                retry = true;
                isReachable = false;
            } catch (PortUnreachableException e) {
                result = (e.getMessage() + "[PortUnreachableException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket close failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(TCP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:org.openqa.selenium.remote.ReusingSocketSocketFactory.java

public Socket createSocket() {
    final Socket socket = new Socket();
    try {/* w  w  w  .j a v a 2 s.com*/
        socket.setReuseAddress(true); // This is added by kristian
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    return socket;

}

From source file:com.predic8.membrane.core.transport.http.Connection.java

public static Connection open(InetAddress host, int port, String localHost, SSLProvider sslProvider,
        ConnectionManager mgr, int connectTimeout) throws UnknownHostException, IOException {
    Connection con = new Connection(mgr);

    if (sslProvider != null) {
        if (isNullOrEmpty(localHost))
            con.socket = sslProvider.createSocket(host, port, connectTimeout);
        else/*  w w  w .j a  v  a  2s .  c  o  m*/
            con.socket = sslProvider.createSocket(host, port, InetAddress.getByName(localHost), 0,
                    connectTimeout);
    } else {
        if (isNullOrEmpty(localHost)) {
            con.socket = new Socket();
        } else {
            con.socket = new Socket();
            con.socket.bind(new InetSocketAddress(InetAddress.getByName(localHost), 0));
        }
        con.socket.connect(new InetSocketAddress(host, port), connectTimeout);
    }

    log.debug("Opened connection on localPort: " + con.socket.getLocalPort());
    //Creating output stream before input stream is suggested.
    con.out = new BufferedOutputStream(con.socket.getOutputStream(), 2048);
    con.in = new BufferedInputStream(con.socket.getInputStream(), 2048);

    return con;
}

From source file:hd3gtv.as5kpc.Serverchannel.java

private Socket connect() throws IOException {
    Socket socket = new Socket();
    socket.setKeepAlive(false);/*from  www  .j a  v  a  2 s . c  o  m*/
    socket.connect(new InetSocketAddress(server, port), 4000);
    return socket;
}

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 {//  w  ww . j av a 2s  .co 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:example.springdata.cassandra.util.RequiresCassandraKeyspace.java

@Override
protected void before() throws Throwable {

    try (Socket socket = new Socket()) {
        socket.setTcpNoDelay(true);/*  w  w w  .  ja v  a  2  s.co  m*/
        socket.setSoLinger(true, 0);
        socket.connect(new InetSocketAddress(host, port), timeout);

    } catch (Exception e) {
        throw new AssumptionViolatedException(
                String.format("Seems as Cassandra is not running at %s:%s.", host, port), e);
    }

    Cluster cluster = Cluster.builder().addContactPoint(host).withPort(port)
            .withNettyOptions(new NettyOptions() {
                @Override
                public void onClusterClose(EventLoopGroup eventLoopGroup) {
                    eventLoopGroup.shutdownGracefully(0, 0, TimeUnit.MILLISECONDS).syncUninterruptibly();
                }
            }).build();

    Session session = cluster.newSession();

    try {

        if (requiresVersion != null) {

            Version cassandraReleaseVersion = CassandraVersion.getReleaseVersion(session);

            if (cassandraReleaseVersion.isLessThan(requiresVersion)) {
                throw new AssumptionViolatedException(
                        String.format("Cassandra at %s:%s runs in Version %s but we require at least %s", host,
                                port, cassandraReleaseVersion, requiresVersion));
            }
        }

        session.execute(String.format(
                "CREATE KEYSPACE IF NOT EXISTS %s \n"
                        + "WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };",
                keyspaceName));
    } finally {
        session.close();
        cluster.close();
    }
}

From source file:com.juick.android.JASocketClient.java

public boolean connect(String host, int port) {
    try {/*from w ww .java  2 s  .  c o  m*/
        log("JASocketClient:" + name + ": new");
        sock = new Socket();
        sock.setSoTimeout(60000); // 1 minute timeout; to check missing pongs and drop connection
        sock.connect(new InetSocketAddress(host, port));
        is = sock.getInputStream();
        os = sock.getOutputStream();
        log("connected");
        return true;
    } catch (Throwable e) {
        log("connect:" + e.toString());
        System.err.println(e);
        //e.printStackTrace();
        return false;
    }
}

From source file:com.googlecode.jsendnsca.NagiosPassiveCheckSender.java

private Socket connectedToNagios() throws IOException {
    Socket socket = new Socket();
    socket.connect(new InetSocketAddress(nagiosSettings.getNagiosHost(), nagiosSettings.getPort()),
            nagiosSettings.getConnectTimeout());
    socket.setSoTimeout(nagiosSettings.getTimeout());
    return socket;
}

From source file:hudson.plugins.chainreactorclient.ChainReactorInvalidServerException.java

public boolean connect(ChainReactorServer server) {
    try {/*w w  w .  j  a v a  2 s  .  c o  m*/
        InetSocketAddress sockaddr = server.getSocketAddress();
        Socket sock = new Socket();
        sock.setSoTimeout(2000);
        sock.connect(sockaddr, 2000);
        BufferedReader rd = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
        ensureValidServer(rd);
        logger.println("Connected to chain reactor server");
        sendBuildInfo(wr);
        rd.close();
        wr.close();
        sock.close();
    } catch (UnknownHostException uhe) {
        logError("Failed to resolve host: " + server.getUrl());
    } catch (SocketTimeoutException ste) {
        logError("Time out while trying to connect to " + server.toString());
    } catch (IOException ioe) {
        logError(ioe.getMessage());
    } catch (ChainReactorInvalidServerException crise) {
        logError(crise.getMessage());
    }

    return true;
}