A simple network client that establishes a network connection to a specified port on a specified host, send an optional message across the connection : Socket « Network Protocol « Java

A simple network client that establishes a network connection to a specified port on a specified host, send an optional message across the connection

 * Copyright (c) 2004 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 3nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose,
 * including teaching and use in open-source projects.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book, 
 * please visit http://www.davidflanagan.com/javaexamples3.
//package je3.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;

 * A simple network client that establishes a network connection to a specified
 * port on a specified host, send an optional message across the connection,
 * reads the response from the server and exits. A suitable client for simple
 * network services like the daytime or finger.
public class Connect {
  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

      // 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
    } 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...");


Related examples in the same category

1.Create a socket without a timeout
2.Create a socket with a timeout
3.Demonstrate Sockets.
4.Socket connection and concurrent package
5.XML based message
6.ObjectInputStream and ObjectOutputStream from Socket
7.ServerSocket and Socket for Serializable object
8.String based communication between Socket
9.Get email with Socket
10.Create PrintWriter from BufferedWriter, OutputStreamWriter and Socket
11.Read from server
12.Use Socket to read and write stream
13.Connects to a server at a specified host and port. It reads text from the console and sends it to the server
14.Reading Text from a Socket
15.Writing Text to a Socket
16.Sending a POST Request Using a Socket
17.Get the Date from server
18.Transfer a file via Socket
19.Ping a server
20.Read and write through socket
21.Read float number from a Socket
22.Read Object from Socket
23.deleting messages from a POP3 mailbox based on message size and Subject line
24.A timeout feature on socket connections
25.Write Objects From Socket
26.Write Double Using Sockets
27.Download WWW Page
28.Redirects incoming TCP connections to other hosts/ports
29.Socket Fetcher
30.Socket Address Encoder
31.Zip socket
32.This program shows how to interrupt a socket channel.
33.This program shows how to use sockets to send plain text mail messages.
34.Makes a socket connection to the atomic clock in Boulder, Colorado, and prints the time that the server sends.