Connects to a server at a specified host and port. It reads text from the console and sends it to the server : Socket « Network Protocol « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Network Protocol » SocketScreenshots 
Connects to a server at a specified host and port. It reads text from the console and sends it to the server
     
 
/*
 * 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.io.Reader;
import java.net.Socket;

/**
 * This program connects to a server at a specified host and port. It reads text
 * from the console and sends it to the server. It reads text from the server
 * and sends it to the console.
 */
public class GenericClient {
  public static void main(String[] argsthrows IOException {
    try {
      // 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>");
    }
  }
}

   
    
    
    
    
  
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. A simple network client that establishes a network connection to a specified port on a specified host, send an optional message across the connection
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
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.