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(InetAddress address, int port) throws IOException 

Source Link

Document

Creates a stream socket and connects it to the specified port number at the specified IP address.

Usage

From source file:io.dacopancm.socketdcm.net.StreamSocket.java

public ObservableList<StreamFile> getStreamList() {
    ObservableList<StreamFile> list = FXCollections.observableArrayList();
    try {//from www  .ja va2s .  c o m

        if (ConectType.GET_STREAMLIST.name().equalsIgnoreCase(method)) {
            logger.log(Level.INFO, "get stream list call");
            sock = new Socket(ip, port);

            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            dOut.writeUTF(ConectType.STREAM.name());//send stream type
            dOut.writeUTF("uncompressed");//send comprimido o no

            dOut.writeUTF(ConectType.GET_STREAMLIST.toString()); //send type
            dOut.writeUTF("mayra");
            dOut.flush(); // Send off the data
            System.out.println("Request list send");
            String resp = dIn.readUTF();
            dOut.close();
            logger.log(Level.INFO, "resp get streamlist: {0}", resp);
            List<StreamFile> files = HelperUtil.fromJSON(resp);
            list.addAll(files);

        }
    } catch (IOException ex) {
        HelperUtil.showErrorB("No se pudo establecer conexin");
        logger.log(Level.INFO, "get streamlist error no connect:{0}", ex.getMessage());
        try {
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
        }

    }
    return list;
}

From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java

public MatcherKState requestState(InetAddress host, int port, String id)
        throws JSONException, InterruptedException, IOException {
    int trials = 120;
    int timeout = 500;
    Socket client = null;//ww  w. j av  a  2 s  . c  o  m

    while (client == null || !client.isConnected()) {
        try {
            client = new Socket(host, port);
        } catch (IOException e) {
            Thread.sleep(timeout);

            if (trials == 0) {
                logger.error(e.getMessage());
                client.close();
                throw new IOException();
            } else {
                trials -= 1;
            }
        }
    }

    JSONObject json = new JSONObject();
    json.put("id", id);

    PrintWriter writer = new PrintWriter(client.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
    writer.println(json.toString());
    writer.flush();

    String code = reader.readLine();
    assertEquals("SUCCESS", code);

    String response = reader.readLine();
    client.close();

    return new MatcherKState(new JSONObject(response), new MatcherFactory(TrackerControl.getServer().getMap()));
}

From source file:com.alibaba.dragoon.common.protocol.transport.socket.SocketConnector.java

public Future<DragoonSession> connect(final SocketAddress address, final MessageHandler messageHandler) {
    if (address == null) {
        throw new IllegalArgumentException("address is null");
    }//w  ww  .j  a  v  a  2  s.co  m

    if (!(address instanceof InetSocketAddress)) {
        throw new IllegalArgumentException("address must be VmPipeAddress.");
    }

    final InetSocketAddress inetSocketAddress = (InetSocketAddress) address;

    FutureTask<DragoonSession> task = new FutureTask<DragoonSession>(new Callable<DragoonSession>() {

        public DragoonSession call() throws Exception {
            connectCount.incrementAndGet();
            if (LOG.isInfoEnabled()) {
                LOG.info("CONNECT TO " + inetSocketAddress);
            }

            remoteAddress = inetSocketAddress.toString();
            Socket socket = new Socket(inetSocketAddress.getAddress(), inetSocketAddress.getPort());

            connectEstablishedCount.incrementAndGet();

            if (LOG.isInfoEnabled()) {
                LOG.info("CONNECTED TO " + inetSocketAddress);
            }

            SocketSessionImpl impl = new SocketSessionImpl(socket, receivedBytes, receivedMessages, sentBytes,
                    sentMessages);

            final long sessionId = generateSessionId();

            DragoonSession session = new DragoonSession(sessionId, new DragoonSessionConfig(messageHandler),
                    impl);
            impl.init(session);

            return session;
        }

    });
    connectorExecutor.submit(task);

    return task;
}

From source file:com.mendhak.gpslogger.common.network.CertificateValidationWorkflow.java

@Override
public void run() {
    try {//w w  w  .  j a  v a2  s  .c  o  m

        LOG.debug("Beginning certificate validation - will connect directly to {} port {}", host,
                String.valueOf(port));

        try {
            LOG.debug("Trying handshake first in case the socket is SSL/TLS only");
            connectToSSLSocket(null);
            postValidationHandler.post(new Runnable() {
                @Override
                public void run() {
                    onWorkflowFinished(context, null, true);
                }
            });
        } catch (final Exception e) {

            if (Networks.extractCertificateValidationException(e) != null) {
                throw e;
            }

            LOG.debug("Direct connection failed or no certificate was presented", e);

            if (serverType == ServerType.HTTPS) {
                postValidationHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        onWorkflowFinished(context, e, false);
                    }
                });
                return;
            }

            LOG.debug("Now attempting to connect over plain socket");
            Socket plainSocket = new Socket(host, port);
            plainSocket.setSoTimeout(30000);
            BufferedReader reader = new BufferedReader(new InputStreamReader(plainSocket.getInputStream()));
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(plainSocket.getOutputStream()));
            String line;

            if (serverType == ServerType.SMTP) {
                LOG.debug("CLIENT: EHLO localhost");
                writer.write("EHLO localhost\r\n");
                writer.flush();
                line = reader.readLine();
                LOG.debug("SERVER: " + line);
            }

            String command = "", regexToMatch = "";
            if (serverType == ServerType.FTP) {

                LOG.debug("FTP type server");
                command = "AUTH SSL\r\n";
                regexToMatch = "(?:234.*)";

            } else if (serverType == ServerType.SMTP) {

                LOG.debug("SMTP type server");
                command = "STARTTLS\r\n";
                regexToMatch = "(?i:220 .* Ready.*)";

            }

            LOG.debug("CLIENT: " + command);
            LOG.debug("(Expecting regex {} in response)", regexToMatch);
            writer.write(command);
            writer.flush();
            while ((line = reader.readLine()) != null) {
                LOG.debug("SERVER: " + line);
                if (line.matches(regexToMatch)) {
                    LOG.debug("Elevating socket and attempting handshake");
                    connectToSSLSocket(plainSocket);
                    postValidationHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            onWorkflowFinished(context, null, true);
                        }
                    });
                    return;
                }
            }

            LOG.debug("No certificates found.  Giving up.");
            postValidationHandler.post(new Runnable() {
                @Override
                public void run() {
                    onWorkflowFinished(context, null, false);
                }
            });
        }

    } catch (final Exception e) {

        LOG.debug("", e);
        postValidationHandler.post(new Runnable() {
            @Override
            public void run() {
                onWorkflowFinished(context, e, false);
            }
        });
    }

}

From source file:de.taimos.gpsd4java.backend.GPSdEndpoint.java

/**
 * Instantiate this class to connect to a GPSd server
 * /*w ww  . j  a  va2  s .  com*/
 * @param server
 *            the server name or IP
 * @param port
 *            the server port
 * @param resultParser
 * @throws UnknownHostException
 * @throws IOException
 */
public GPSdEndpoint(final String server, final int port, final AbstractResultParser resultParser)
        throws UnknownHostException, IOException {
    this.server = server;
    this.port = port;
    if (server == null) {
        throw new IllegalArgumentException("server can not be null!");
    }
    if ((port < 0) || (port > 65535)) {
        throw new IllegalArgumentException("Illegal port number: " + port);
    }
    if (resultParser == null) {
        throw new IllegalArgumentException("resultParser can not be null!");
    }

    this.socket = new Socket(server, port);
    this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
    this.out = new BufferedWriter(new OutputStreamWriter(this.socket.getOutputStream()));
    this.resultParser = resultParser;
}

From source file:info.bonjean.quinkana.Main.java

private static void run(String[] args) throws QuinkanaException {
    Properties properties = new Properties();
    InputStream inputstream = Main.class.getResourceAsStream("/config.properties");

    try {//  w w  w  . j  a v a  2 s  .c  om
        properties.load(inputstream);
        inputstream.close();
    } catch (IOException e) {
        throw new QuinkanaException("cannot load internal properties", e);
    }

    String name = (String) properties.get("name");
    String description = (String) properties.get("description");
    String url = (String) properties.get("url");
    String version = (String) properties.get("version");
    String usage = (String) properties.get("help.usage");
    String defaultHost = (String) properties.get("default.host");
    int defaultPort = Integer.valueOf(properties.getProperty("default.port"));

    ArgumentParser parser = ArgumentParsers.newArgumentParser(name).description(description)
            .epilog("For more information, go to " + url).version("${prog} " + version).usage(usage);
    parser.addArgument("ACTION").type(Action.class).choices(Action.tail, Action.list).dest("action");
    parser.addArgument("-H", "--host").setDefault(defaultHost)
            .help(String.format("logstash host (default: %s)", defaultHost));
    parser.addArgument("-P", "--port").type(Integer.class).setDefault(defaultPort)
            .help(String.format("logstash TCP port (default: %d)", defaultPort));
    parser.addArgument("-f", "--fields").nargs("+").help("fields to display");
    parser.addArgument("-i", "--include").nargs("+").help("include filter (OR), example host=example.com")
            .metavar("FILTER").type(Filter.class);
    parser.addArgument("-x", "--exclude").nargs("+")
            .help("exclude filter (OR, applied after include), example: severity=debug").metavar("FILTER")
            .type(Filter.class);
    parser.addArgument("-s", "--single").action(Arguments.storeTrue()).help("display single result and exit");
    parser.addArgument("--version").action(Arguments.version()).help("output version information and exit");

    Namespace ns = parser.parseArgsOrFail(args);

    Action action = ns.get("action");
    List<String> fields = ns.getList("fields");
    List<Filter> includes = ns.getList("include");
    List<Filter> excludes = ns.getList("exclude");
    boolean single = ns.getBoolean("single");
    String host = ns.getString("host");
    int port = ns.getInt("port");

    final Socket clientSocket;
    final InputStream is;
    try {
        clientSocket = new Socket(host, port);
        is = clientSocket.getInputStream();
    } catch (IOException e) {
        throw new QuinkanaException("cannot connect to the server " + host + ":" + port, e);
    }

    // add a hook to ensure we clean the resources when leaving
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                clientSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    // prepare JSON parser
    ObjectMapper mapper = new ObjectMapper();
    JsonFactory jsonFactory = mapper.getFactory();
    JsonParser jp;
    try {
        jp = jsonFactory.createParser(is);
    } catch (IOException e) {
        throw new QuinkanaException("error during JSON parser creation", e);
    }

    JsonToken token;

    // action=list
    if (action.equals(Action.list)) {
        try {
            // do this in a separate loop to not pollute the main loop
            while ((token = jp.nextToken()) != null) {
                if (token != JsonToken.START_OBJECT)
                    continue;

                // parse object
                JsonNode node = jp.readValueAsTree();

                // print fields
                Iterator<String> fieldNames = node.fieldNames();
                while (fieldNames.hasNext())
                    System.out.println(fieldNames.next());

                System.exit(0);
            }
        } catch (IOException e) {
            throw new QuinkanaException("error during JSON parsing", e);
        }
    }

    // action=tail
    try {
        while ((token = jp.nextToken()) != null) {
            if (token != JsonToken.START_OBJECT)
                continue;

            // parse object
            JsonNode node = jp.readValueAsTree();

            // filtering (includes)
            if (includes != null) {
                boolean skip = true;
                for (Filter include : includes) {
                    if (include.match(node)) {
                        skip = false;
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            // filtering (excludes)
            if (excludes != null) {
                boolean skip = false;
                for (Filter exclude : excludes) {
                    if (exclude.match(node)) {
                        skip = true;
                        break;
                    }
                }
                if (skip)
                    continue;
            }

            // if no field specified, print raw output (JSON)
            if (fields == null) {
                System.out.println(node.toString());
                if (single)
                    break;
                continue;
            }

            // formatted output, build and print the string
            StringBuilder sb = new StringBuilder(128);
            for (String field : fields) {
                if (sb.length() > 0)
                    sb.append(" ");

                if (node.get(field) != null && node.get(field).textValue() != null)
                    sb.append(node.get(field).textValue());
            }
            System.out.println(sb.toString());

            if (single)
                break;
        }
    } catch (IOException e) {
        throw new QuinkanaException("error during JSON parsing", e);
    }
}

From source file:dk.netarkivet.viewerproxy.WebProxyTester.java

@Before
public void setUp() throws IOException {
    // Check port not in use (since this will fail all tests)

    httpPort = Settings.getInt(CommonSettings.HTTP_PORT_NUMBER);
    if (httpPort < 1025 || httpPort > 65535) {
        fail("Port must be in the range 1025-65535, not " + httpPort);
    }/*  w ww. j  a  v a 2 s  . c  o  m*/
    try {
        new Socket(InetAddress.getLocalHost(), httpPort);
        fail("Port already in use before unit test");
    } catch (IOException e) {
        // Expected
    }

    uriResolverMock = mock(URIResolver.class);
    /*
            requestMock = mock(org.eclipse.jetty.server.Request.class);
            responseMock = mock(org.eclipse.jetty.server.Response.class);
    */
    requestMock = mock(org.mortbay.jetty.Request.class);
    responseMock = mock(org.mortbay.jetty.Response.class);

}

From source file:com.jkoolcloud.jesl.net.socket.SocketClient.java

/**
 * {@inheritDoc}/*  w  w  w  .  j a  v  a  2 s .c  o  m*/
 */
@Override
public synchronized void connect() throws IOException {
    if (isConnected())
        return;
    if (secure) {
        SocketFactory socketFactory = SSLSocketFactory.getDefault();
        socket = socketFactory.createSocket(host, port);
    } else {
        socket = new Socket(host, port);
    }
    out = new DataOutputStream(socket.getOutputStream());
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

From source file:edu.mit.scratch.ScratchCloudSession.java

public ScratchCloudSession(final ScratchSession session, final String cloudToken, final int projectID)
        throws ScratchProjectException {
    this.session = session;
    this.cloudToken = cloudToken; // if !work, md5 cloudToken
    this.projectID = projectID;
    this.hashToken = this.MD5(this.getCloudToken());

    Socket socket = null;/*from  w  w w  . j a va2 s  . com*/
    PrintWriter out = null;
    BufferedReader in = null;

    try {
        socket = new Socket(Scratch.CLOUD_SERVER, Scratch.CLOUD_PORT);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        this.socket = socket;
        this.out = out;
        this.in = in;

        this.thread = new Thread(() -> {
            while (ScratchCloudSession.this.running) {
                String line = "";
                try {
                    line = ScratchCloudSession.this.in.readLine();
                } catch (final IOException e) {
                    e.printStackTrace();
                }
                if (line != null)
                    if (!line.equals("null") && !line.equals("{}"))
                        ScratchCloudSession.this.handleLine(line);

            }
        });
        this.thread.start();

        this.handshake();
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

}

From source file:SmtpTalk.java

/**
 * Constructor taking a server hostname as argument.
 *///from w  ww. j  a va  2  s.  com
SmtpTalk(String server) throws Exception {
    host = server;
    try {
        Socket s = new Socket(host, 25);
        is = new BufferedReader(new InputStreamReader(s.getInputStream()));
        os = new PrintStream(s.getOutputStream());
    } catch (NoRouteToHostException e) {
        die("No route to host " + host);
    } catch (ConnectException e) {
        die("Connection Refused by " + host);
    } catch (UnknownHostException e) {
        die("Unknown host " + host);
    } catch (IOException e) {
        die("I/O error setting up socket streams\n" + e);
    }
}