Java
  Home arrow Java arrow Page 2 - Socket Programming in Java
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Socket Programming in Java
By: A.P.Rajshekhar
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 80
    2007-04-17

    Table of Contents:
  • Socket Programming in Java
  • Socket programming, step by step
  • Socket programming in the real world
  • Socket programming in the real world, continued

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Socket Programming in Java - Socket programming, step by step


    (Page 2 of 4 )

    Any net enabled application has two important parts: the code that executes at client-side and the code that executes at server-side. So using the functionality of sockets can be partitioned into two major steps:

    1. The server or the server-side code
    2. The client or the client-side code

    The multi-threaded nature of former can always be guaranteed whereas the later may or may not be multi-threaded.

    The Server

    The server's main function is to wait for incoming requests, and to service them when they come in. So the code to implement the server can be further broken down to the following steps:

    1.  Establish a server that monitors a particular port. This is done by creating an instance of the ServerSocket class. There are four different ways to create an instance of ServerSocket. They are:

    a. ServerSocket(),  which simply sets the implementation that means everything is taken as default values. 

    b. ServerSocket(int port), which creates a server-side socket and binds the socket to the given port number.

    c. ServerSocket(int port, int backlog), which not only binds the created socket to the port but also create a queue of length specified by the number passed as the backlog parameter. 

    d. ServerSocket(int port, int backlog, InetAddress bindAddr), which creates a server-side socket that is bound to the specified port number with the queue of length specified by the backlog and bound to the address specified by the bindAddr argument.

    So to create a socket bound to port number 8888 with a backlog queue of size 5 and bound with address of local host the statement would be:

    ServerSocket server = new ServerSocket(8888, 5, InetAddress.getLocalHost() );

    One point to keep in mind is that the above mentioned constructors return TCP sockets and not UDP sockets.

    2.  The next step is to tell the newly created server socket to listen indefinitely and accept incoming requests. This is done by using the accept() method of ServerSocket class. When a request comes, accept() returns a Socket object representing the connection. In code it would be:

    Socket incoming = server.accept();

    3.  Communicating with the socket, which means reading from and writing to the Socket object. To communicate with a Socket object, two tasks have to be performed. First the Input and Output stream corresponding to the Socket object has to be obtained. That can be done by using the getInputStream() and getOutputStream() methods of Socket class. In code it would be:

    BufferedReader in = new BufferedReader
     
    (new InputStreamReader(incoming.getInputStream()));
    PrintWriter out = new PrintWriter
     
    (incoming.getOutputStream(), true /* autoFlush */);

    The second task is to read from and write to the Socket object. Since the communication has to continue until the client breaks the connection, the reading from and writing to is done within a loop, like this:

    boolean done = false;
     
    while (!done)
       
    {
         
    String line = in.readLine();
         
    if (line == null) done = true;
         
    else
         
    {
           
    out.println("Echo: " + line); 

            if (line.trim().equals("BYE"))
             
    done = true;
         
    }
       
    }

    The actual syntax for reading and writing is not different from the I/O done for simple files.

    4.  Once the client breaks the connection or stops sending the request, the Socket object representing the client has to be closed. This can be done by calling close() method on the Socket object. The statement would be:

    incoming.close();

    That's how a server is coded. The next section deals with creating a client.

    The Client

    The main purpose of the client is to connect to the server and communicate with it using the connection. So coding a client requires the following steps: 

    1. Connect to the server. Connecting to the server can be accomplished in two steps:

    a.  Creating a Socket object. The socket at client side just needs to know the host name (the name of the machine where server is running) and the port where the server is listening. To create a Socket object, there are seven constructors provided by the Socket class, of which the most commonly used are:

    • Socket(), which creates a new Socket instance without connecting to host.
    • Socket(InetAddress address, int port), which creates a new Socket object and connects to the port specified at the given address.
    • Socket(java.lang.String host, int port), which works the same way as Socket(), except that instead of an address, the host name is used.

    So to create a Socket object that connects to 'localhost' at 8888, the statement would be:

    Socket s=new Socket("localhost",8888);

    b.   Connecting  to the server comes into picture if no argument constructor is used. It takes the object of the SocketAddress object as an argument. So to connect to localhost at port 8888, the code would be:

    Socket s= new Socket();
    s.connect(new SocketAddress("localhost",8888));

     2.  Communicating with the server. Communicating with the server using a socket at client side is no different from how the server communicates with the client. First, the input and output streams connected with the Socket object are to be retrieved thus:

    BufferedReader in = new BufferedReader
     
    (new InputStreamReader(s.getInputStream()));
    PrintWriter out = new PrintWriter
     
    (s.getOutputStream(), true /* autoFlush */);

    Then you read and write using the corresponding streams. For example, if the client just waits for the data sent by the server, the code would be

    boolean more = true;
    while (more)
     
    {
       
    String line = in.readLine();
       
    if (line == null)
         
    more = false;
       
    else
         
    System.out.println(line);
     
    }

    That covers all the steps involved in creating a network enabled application. In the next section I will be developing a file server application with multi-threading to handle multiple clients.

    More Java Articles
    More By A.P.Rajshekhar


       · In this article I have discussed basics of sockets and how to program TCP sockets...
       · What version of JAVA did you used in this exampple. I've been trying to test the...
       · HiCan you tell me which OS are you using as the distro of Linux that I am using...
       · I assume you mean to do more than that
       · Here is 'more than...
       · Hi This is excellent article. I want to use Unix socket communication. How to do...
       · with java 1.5 instead of using TextReader you can also try BufferedReader class for...
     

    JAVA ARTICLES

    - Deploying Multiple Java Applets as One
    - Deploying Java Applets
    - Understanding Deployment Frameworks
    - Database Programming in Java Using JDBC
    - Extension Interfaces and SAX
    - Entities, Handlers and SAX
    - Advanced SAX
    - Conversions and Java Print Streams
    - Formatters and Java Print Streams
    - Java Print Streams
    - Wildcards, Arrays, and Generics in Java
    - Wildcards and Generic Methods in Java
    - Finishing the Project: Java Web Development ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    Stay green...Green IT