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

public static void main(String[] args) throws IOException {
    try {/*from   w w  w  .j a  va2  s.  co  m*/
        // Check the number of arguments
        if (args.length != 2)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the host and port specifications
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Connect to the specified host and port
        Socket s = new Socket(host, port);

        // Set up streams for reading from and writing to the server.
        // The from_server stream is final for use in the inner class below
        final Reader from_server = new InputStreamReader(s.getInputStream());
        PrintWriter to_server = new PrintWriter(s.getOutputStream());

        // Set up streams for reading from and writing to the console
        // The to_user stream is final for use in the anonymous class below
        BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in));
        // Pass true for auto-flush on println()
        final PrintWriter to_user = new PrintWriter(System.out, true);

        // Tell the user that we've connected
        to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort());

        // Create a thread that gets output from the server and displays
        // it to the user. We use a separate thread for this so that we
        // can receive asynchronous output
        Thread t = new Thread() {
            public void run() {
                char[] buffer = new char[1024];
                int chars_read;
                try {
                    // Read characters from the server until the
                    // stream closes, and write them to the console
                    while ((chars_read = from_server.read(buffer)) != -1) {
                        to_user.write(buffer, 0, chars_read);
                        to_user.flush();
                    }
                } catch (IOException e) {
                    to_user.println(e);
                }

                // When the server closes the connection, the loop above
                // will end. Tell the user what happened, and call
                // System.exit(), causing the main thread to exit along
                // with this one.
                to_user.println("Connection closed by server.");
                System.exit(0);
            }
        };

        // Now start the server-to-user thread
        t.start();

        // In parallel, read the user's input and pass it on to the server.
        String line;
        while ((line = from_user.readLine()) != null) {
            to_server.print(line + "\r\n");
            to_server.flush();
        }

        // If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end
        // their input, we'll get an EOF, and the loop above will exit.
        // When this happens, we stop the server-to-user thread and close
        // the socket.

        s.close();
        to_user.println("Connection closed by client.");
        System.exit(0);
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java GenericClient <hostname> <port>");
    }
}

From source file:Connect.java

public static void main(String[] args) {
    try { // Handle exceptions below
        // Get our command-line arguments
        String hostname = args[0];
        int port = Integer.parseInt(args[1]);
        String message = "";
        if (args.length > 2)
            for (int i = 2; i < args.length; i++)
                message += args[i] + " ";

        // Create a Socket connected to the specified host and port.
        Socket s = new Socket(hostname, port);

        // Get the socket output stream and wrap a PrintWriter around it
        PrintWriter out = new PrintWriter(s.getOutputStream());

        // Sent the specified message through the socket to the server.
        out.print(message + "\r\n");
        out.flush(); // Send it now.

        // Get an input stream from the socket and wrap a BufferedReader
        // around it, so we can read lines of text from the server.
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

        // Before we start reading the server's response tell the socket
        // that we don't want to wait more than 3 seconds
        s.setSoTimeout(3000);//from   w  ww  . j a v  a  2s  .c  o m

        // Now read lines from the server until the server closes the
        // connection (and we get a null return indicating EOF) or until
        // the server is silent for 3 seconds.
        try {
            String line;
            while ((line = in.readLine()) != null)
                // If we get a line
                System.out.println(line); // print it out.
        } catch (SocketTimeoutException e) {
            // We end up here if readLine() times out.
            System.err.println("Timeout; no response from server.");
        }

        out.close(); // Close the output stream
        in.close(); // Close the input stream
        s.close(); // Close the socket
    } catch (IOException e) { // Handle IO and network exceptions here
        System.err.println(e);
    } catch (NumberFormatException e) { // Bad port number
        System.err.println("You must specify the port as a number");
    } catch (ArrayIndexOutOfBoundsException e) { // wrong # of args
        System.err.println("Usage: Connect <hostname> <port> message...");
    }
}

From source file:com.googlecode.shutdownlistener.ShutdownUtility.java

public static void main(String[] args) throws Exception {
    final ShutdownConfiguration config = ShutdownConfiguration.getInstance();

    final String command;
    if (args.length > 0) {
        command = args[0];/*from   w  w  w  .  j a va  2  s .  co  m*/
    } else {
        command = config.getStatusCommand();
    }

    System.out.println("Calling " + config.getHost() + ":" + config.getPort() + " with command: " + command);

    final InetAddress hostAddress = InetAddress.getByName(config.getHost());
    final Socket shutdownConnection = new Socket(hostAddress, config.getPort());
    try {
        shutdownConnection.setSoTimeout(5000);
        final BufferedReader reader = new BufferedReader(
                new InputStreamReader(shutdownConnection.getInputStream()));
        final PrintStream writer = new PrintStream(shutdownConnection.getOutputStream());
        try {
            writer.println(command);
            writer.flush();

            while (true) {
                final String line = reader.readLine();
                if (line == null) {
                    break;
                }

                System.out.println(line);
            }
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(writer);
        }
    } finally {
        try {
            shutdownConnection.close();
        } catch (IOException ioe) {
        }
    }

}

From source file:jetbrains.exodus.util.ForkedProcessRunner.java

@SuppressWarnings({ "HardcodedFileSeparator" })
public static void main(String[] args) throws Exception {
    log.info("Process started. Arguments: " + Arrays.toString(args));
    if (args.length < 2) {
        exit("Arguments do not contain port number and/or class to be run. Exit.", null);
    }//from  w ww.  ja  v  a 2 s  .  c  o  m
    try {
        int port = Integer.parseInt(args[0]);
        socket = new Socket("localhost", port);
        streamer = new Streamer(socket);
    } catch (NumberFormatException e) {
        exit("Failed to parse port number: " + args[0] + ". Exit.", null);
    }
    ForkedLogic forkedLogic = null;
    try {
        Class<?> clazz = Class.forName(args[1]);
        forkedLogic = (ForkedLogic) clazz.getConstructor().newInstance();
    } catch (Exception e) {
        exit("Failed to instantiate or initialize ForkedLogic descendant", e);
    }
    // lets provide the peer with our process id
    streamer.writeString(getProcessId());
    String[] realArgs = new String[args.length - 2];
    System.arraycopy(args, 2, realArgs, 0, realArgs.length);
    forkedLogic.forked(realArgs);
}

From source file:com.web.server.ShutDownServer.java

/**
 * @param args/*from  w w w . j a  va 2 s. c o  m*/
 * @throws SAXException 
 * @throws IOException 
 */
public static void main(String[] args) throws IOException, SAXException {
    DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/serverconfig-rules.xml")));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
    Digester serverdigester = serverdigesterLoader.newDigester();
    ServerConfig serverconfig = (ServerConfig) serverdigester
            .parse(new InputSource(new FileInputStream("./config/serverconfig.xml")));
    try {
        Socket socket = new Socket("localhost", Integer.parseInt(serverconfig.getShutdownport()));
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
        outputStream.close();
    } catch (IOException e1) {

        e1.printStackTrace();
    }

}

From source file:com.alexjalg.gson_google.EjecutarHttpClient.java

public static void main(String[] args) throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("jsonplaceholder.typicode.com", 80);
    coreContext.setTargetHost(host);//from   ww  w . j  a  v  a 2 s  .  c o  m

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {
        String[] targets = { "/posts" };
        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());

            //                System.out.println(EntityUtils.toString(response.getEntity()));
            String json = EntityUtils.toString(response.getEntity());

            ArrayList<Posts> listPosts = new ArrayList<Posts>();
            Type listType = new TypeToken<ArrayList<Posts>>() {
            }.getType();
            listPosts = new Gson().fromJson(json, listType);

            for (Posts post : listPosts) {
                System.out.println("");
                System.out.println(post.getUserId());
                System.out.println(post.getId());
                System.out.println(post.getTitle());
                System.out.println(post.getBody());
            }

            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}

From source file:com.app.server.ShutDownServer.java

/**
 * @param args//from ww w . j  a v a  2 s. c  om
 * @throws SAXException 
 * @throws IOException 
 */
public static void main(String[] args) throws IOException, SAXException {
    DigesterLoader serverdigesterLoader = DigesterLoader.newLoader(new FromXmlRulesModule() {

        protected void loadRules() {
            // TODO Auto-generated method stub
            try {
                loadXMLRules(new InputSource(new FileInputStream("./config/serverconfig-rules.xml")));
            } catch (FileNotFoundException e) {
                log.error("Could not load rules xml serverconfig-rules.xml", e);
                // TODO Auto-generated catch block
                //e.printStackTrace();
            }

        }
    });
    Digester serverdigester = serverdigesterLoader.newDigester();
    ServerConfig serverconfig = (ServerConfig) serverdigester
            .parse(new InputSource(new FileInputStream("./config/serverconfig.xml")));
    try {
        Socket socket = new Socket("localhost", Integer.parseInt(serverconfig.getShutdownport()));
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
        outputStream.close();
    } catch (Exception ex) {
        log.error("Could not able to create socket and write shutdown bytes", ex);
        //e1.printStackTrace();
    }

}

From source file:Bounce.java

/**
 * The main method./* w w  w . j  a  v  a  2s .  com*/
 */

public static void main(String[] args) {
    if (args.length < 3) {
        printUsage();
        System.exit(1);
    }

    int localPort;
    try {
        localPort = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Bad local port value: " + args[0]);
        printUsage();
        System.exit(2);
        return;
    }

    String hostname = args[1];

    int remotePort;
    try {
        remotePort = Integer.parseInt(args[2]);
    } catch (NumberFormatException e) {
        System.err.println("Bad remote port value: " + args[2]);
        printUsage();
        System.exit(3);
        return;
    }

    boolean shouldLog = args.length > 3 ? Boolean.valueOf(args[3]).booleanValue() : false;
    int numConnections = 0;

    try {
        ServerSocket ssock = new ServerSocket(localPort);
        while (true) {
            Socket incomingSock = ssock.accept();
            Socket outgoingSock = new Socket(hostname, remotePort);
            numConnections++;

            InputStream incomingIn = incomingSock.getInputStream();
            InputStream outgoingIn = outgoingSock.getInputStream();
            OutputStream incomingOut = incomingSock.getOutputStream();
            OutputStream outgoingOut = outgoingSock.getOutputStream();

            if (shouldLog) {
                String incomingLogName = "in-log-" + incomingSock.getInetAddress().getHostName() + "("
                        + localPort + ")-" + numConnections + ".dat";
                String outgoingLogName = "out-log-" + hostname + "(" + remotePort + ")-" + numConnections
                        + ".dat";
                OutputStream incomingLog = new FileOutputStream(incomingLogName);
                incomingOut = new MultiOutputStream(incomingOut, incomingLog);
                OutputStream outgoingLog = new FileOutputStream(outgoingLogName);
                outgoingOut = new MultiOutputStream(outgoingOut, outgoingLog);
            }

            PumpThread t1 = new PumpThread(incomingIn, outgoingOut);
            PumpThread t2 = new PumpThread(outgoingIn, incomingOut);
            t1.start();
            t2.start();
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(3);
    }
}

From source file:EchoClient.java

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

     Socket echoSocket = null;/*from   w  w  w . j  ava 2 s . c  om*/
     PrintWriter out = null;
     BufferedReader in = null;

     try {
         echoSocket = new Socket("taranis", 7);
         out = new PrintWriter(echoSocket.getOutputStream(), true);
         in = new BufferedReader(new InputStreamReader(
                                     echoSocket.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 userInput;

while ((userInput = stdIn.readLine()) != null) {
    out.println(userInput);
    System.out.println("echo: " + in.readLine());
}

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

From source file:cn.heroes.ud.protocol.ElementalHttpGet.java

public static void main(String[] args) throws Exception {
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new RequestContent())
            .add(new RequestTargetHost()).add(new RequestConnControl()).add(new RequestUserAgent("Test/1.1"))
            .add(new RequestExpectContinue(true)).build();

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpCoreContext coreContext = HttpCoreContext.create();
    HttpHost host = new HttpHost("localhost", 8080);
    coreContext.setTargetHost(host);/*from  w w  w.ja v a2s. co  m*/

    DefaultBHttpClientConnection conn = new DefaultBHttpClientConnection(8 * 1024);
    ConnectionReuseStrategy connStrategy = DefaultConnectionReuseStrategy.INSTANCE;

    try {

        String[] targets = { "/", "/servlets-examples/servlet/RequestInfoExample", "/somewhere%20in%20pampa" };

        for (int i = 0; i < targets.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket);
            }
            BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            httpexecutor.preProcess(request, httpproc, coreContext);
            HttpResponse response = httpexecutor.execute(request, conn, coreContext);
            httpexecutor.postProcess(response, httpproc, coreContext);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, coreContext)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}