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:Whois.java

public String whois(String query, String server) throws IOException {
    Socket sock = new Socket(server, 43);
    int c = 0;/*from  www . ja v a 2s .c om*/
    String outstring = "";
    OutputStream os = sock.getOutputStream();
    InputStream is = sock.getInputStream();
    query += "\r\n";
    os.write(query.getBytes("iso8859_1"));
    try {
        while (c != -1) {
            c = is.read();
            if (c != -1)
                outstring += (char) c;
        }
    } catch (IOException e) {
    }
    return outstring;
}

From source file:Main.java

/**
 *
 * Resolve DNS name into IP address//w ww. j a  va  2  s .c o  m
 *
 * @param host DNS name
 * @return IP address in integer format
 * @throws IOException
 */
public static int resolve(String host) throws IOException {
    Socket localSocket = new Socket(ADB_HOST, ADB_PORT);
    DataInputStream dis = new DataInputStream(localSocket.getInputStream());
    OutputStream os = localSocket.getOutputStream();
    int count_read = 0;

    if (localSocket == null || dis == null || os == null)
        return -1;
    String cmd = "dns:" + host;

    if (!sendAdbCmd(dis, os, cmd))
        return -1;

    count_read = dis.readInt();
    localSocket.close();
    return count_read;
}

From source file:com.codefollower.lealone.omid.TestUtils.java

public static void waitForSocketListening(String host, int port, int sleepTimeMillis)
        throws UnknownHostException, IOException, InterruptedException {
    while (true) {
        Socket sock = null;/*from  ww w . jav  a  2  s  . c  om*/
        try {
            sock = new Socket(host, port);
        } catch (IOException e) {
            // ignore as this is expected
            Thread.sleep(sleepTimeMillis);
            continue;
        } finally {
            if (sock != null) {
                sock.close();
            }
        }
        LOG.info("Host " + host + ":" + port + " is up");
        break;
    }
}

From source file:Main.java

/**
 *
 * Get a tcp socket connection to specified IP address and port proxied by adb
 *
 * The proxying is transparent, e.g. if a socket is returned, then it can be written to and
 * read from as if it is directly connected to the target
 *
 * @param remoteAddress IP address of the host to connect to
 * @param remotePort port of the host to connect to
 * @return a valid Socket instance if successful, null otherwise
 *///www .j  a v a  2  s.  c  om
public static Socket getForwardedSocket(int remoteAddress, int remotePort) {
    try {
        Socket socket = new Socket(ADB_HOST, ADB_PORT);
        String cmd = "tcp:" + remotePort + ":" + convert(remoteAddress);
        if (!sendAdbCmd(socket.getInputStream(), socket.getOutputStream(), cmd)) {
            socket.close();
            return null;
        }
        return socket;
    } catch (IOException ioe) {
        Log.w(LOGTAG, "error creating adb socket", ioe);
        return null;
    }
}

From source file:SimpleProxyServer.java

/**
 * runs a single-threaded proxy server on
 * the specified local port. It never returns.
 *///from w  w  w  . ja  va  2s.  c o m
public static void runServer(String host, int remoteport, int localport) throws IOException {
    // Create a ServerSocket to listen for connections with
    ServerSocket ss = new ServerSocket(localport);

    final byte[] request = new byte[1024];
    byte[] reply = new byte[4096];

    while (true) {
        Socket client = null, server = null;
        try {
            // Wait for a connection on the local port
            client = ss.accept();

            final InputStream streamFromClient = client.getInputStream();
            final OutputStream streamToClient = client.getOutputStream();

            // Make a connection to the real server.
            // If we cannot connect to the server, send an error to the
            // client, disconnect, and continue waiting for connections.
            try {
                server = new Socket(host, remoteport);
            } catch (IOException e) {
                PrintWriter out = new PrintWriter(streamToClient);
                out.print("Proxy server cannot connect to " + host + ":" + remoteport + ":\n" + e + "\n");
                out.flush();
                client.close();
                continue;
            }

            // Get server streams.
            final InputStream streamFromServer = server.getInputStream();
            final OutputStream streamToServer = server.getOutputStream();

            // a thread to read the client's requests and pass them
            // to the server. A separate thread for asynchronous.
            Thread t = new Thread() {
                public void run() {
                    int bytesRead;
                    try {
                        while ((bytesRead = streamFromClient.read(request)) != -1) {
                            streamToServer.write(request, 0, bytesRead);
                            streamToServer.flush();
                        }
                    } catch (IOException e) {
                    }

                    // the client closed the connection to us, so close our
                    // connection to the server.
                    try {
                        streamToServer.close();
                    } catch (IOException e) {
                    }
                }
            };

            // Start the client-to-server request thread running
            t.start();

            // Read the server's responses
            // and pass them back to the client.
            int bytesRead;
            try {
                while ((bytesRead = streamFromServer.read(reply)) != -1) {
                    streamToClient.write(reply, 0, bytesRead);
                    streamToClient.flush();
                }
            } catch (IOException e) {
            }

            // The server closed its connection to us, so we close our
            // connection to our client.
            streamToClient.close();
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            try {
                if (server != null)
                    server.close();
                if (client != null)
                    client.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:EZShare.SubscribeCommandConnection.java

public static void establishPersistentConnection(Boolean secure, int port, String ip, int id,
        JSONObject unsubscribJsonObject, String commandname, String name, String owner, String description,
        String channel, String uri, List<String> tags, String ezserver, String secret, Boolean relay,
        String servers) throws URISyntaxException {
    //secure = false;
    try {//  www  .jav  a 2 s  .com
        System.out.print(port + ip);
        Socket socket = null;
        if (secure) {

            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            socket = (SSLSocket) sslsocketfactory.createSocket(ip, port);
        } else {
            socket = new Socket(ip, port);
        }
        BufferedReader Reader = new BufferedReader(new InputStreamReader(System.in));
        DataOutputStream output = new DataOutputStream(socket.getOutputStream());
        DataInputStream input = new DataInputStream(socket.getInputStream());

        JSONObject command = new JSONObject();
        Resource resource = new Resource();
        command = resource.inputToJSON(commandname, id, name, owner, description, channel, uri, tags, ezserver,
                secret, relay, servers);

        output.writeUTF(command.toJSONString());
        Client.debug("SEND", command.toJSONString());
        //output.writeUTF(command.toJSONString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while (true/*(string = input.readUTF()) != null*/) {
                        String serverResponse = input.readUTF();
                        JSONParser parser = new JSONParser();
                        JSONObject response = (JSONObject) parser.parse(serverResponse);
                        Client.debug("RECEIVE", response.toJSONString());
                        //System.out.println(serverResponse);          
                        //                     if((string = Reader.readLine()) != null){
                        //                        if(onKeyPressed(output,string,unsubscribJsonObject)) break;
                        //                     }
                        if (flag == 1) {
                            break;
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                String string = null;
                try {
                    while ((string = Reader.readLine()) != null) {
                        flag = 1;
                        if (onKeyPressed(output, string, unsubscribJsonObject))
                            break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.comcast.viper.flume2storm.zookeeper.ZkTestUtils.java

/**
 * Utility function to send a command to the internal server. ZK servers
 * accepts 4 byte command strings to test their liveness.
 *//* w  w  w.j av a 2s  . com*/
protected static String send4LetterWord(final String host, final int port, final String cmd) {
    Preconditions.checkArgument(cmd.length() == 4);
    try {
        final Socket sock = new Socket(host, port);
        OutputStream outstream = null;
        BufferedReader reader = null;
        try {
            outstream = sock.getOutputStream();
            outstream.write(cmd.getBytes());
            outstream.flush();

            reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            final StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } finally {
            if (outstream != null) {
                outstream.close();
            }
            sock.close();
            if (reader != null) {
                reader.close();
            }
        }
    } catch (final Exception e) {
        System.out.println(e.getMessage());
        return StringUtils.EMPTY;
    }
}

From source file:Client.Connection.java

public Connection(String host, int port) throws IOException {
    s = new Socket(host, port);
    in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    out = new PrintWriter(s.getOutputStream(), true);
}

From source file:EchoClient.java

public static void main(String[] args) throws IOException {

        Socket kkSocket = null;/*from  w  w  w  .j av  a 2  s . c  o m*/
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            kkSocket = new Socket("taranis", 4444);
            out = new PrintWriter(kkSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: taranis.");
            System.exit(1);
        }

        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String fromServer;
        String fromUser;

        while ((fromServer = in.readLine()) != null) {
            System.out.println("Server: " + fromServer);
            if (fromServer.equals("Bye."))
                break;

            fromUser = stdIn.readLine();
            if (fromUser != null) {
                System.out.println("Client: " + fromUser);
                out.println(fromUser);
            }
        }

        out.close();
        in.close();
        stdIn.close();
        kkSocket.close();
    }

From source file:de.root1.logiccollection.offLogicVocESP8266.java

@Override
public void init() {
    this.tt = new TimerTask() {

        @Override/*from   w ww.  j a va 2s. com*/
        public void run() {
            try {
                Socket s = new Socket("nodemcu1", 44444);
                OutputStream out = s.getOutputStream();
                InputStream in = s.getInputStream();
                out.write("\n".getBytes());
                out.flush();

                InputStreamReader isr = new InputStreamReader(in);
                JSONObject data = (JSONObject) JSONValue.parse(isr);
                isr.close();
                out.close();

                int voc = Integer.parseInt(data.get("voc").toString());
                int tvoc = Integer.parseInt(data.get("voc").toString());
                int resistance = Integer.parseInt(data.get("resistance").toString());
                int status = Integer.parseInt(data.get("status").toString());

                log.info("voc={}, tvoc={} resistance={} status={}",
                        new Object[] { voc, tvoc, resistance, status });

                //                    write(ga, String.valueOf(voc));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    };
    setPA("1.1.203");
    t.schedule(tt, 5000, 60000);
    log.info("VOC ESP8266 reader is running.");
}