Comments
Richard Davies wrote: The UK has a good crop of technology pioneers in cloud computing - for example ElasticHosts, FlexiScale, Flexiant, OnApp - and also some strong government initiatives such as G-Cloud. We will have to see whether this kind of technical leadership converts into swift mass-market adoption or not.
Cloud Expo on Google News


2008 West
DIAMOND SPONSOR:
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
GOLD SPONSORS:
Appsense
User Environment Management – The Third Layer of the Desktop
Cordys
Cloud Computing for Business Agility
EMC
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Intel
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Sensedia
Return on Assests: Bringing Visibility to your SOA Strategy
Symantec
Managing Hybrid Endpoint Environments
VMWare
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
PLATINUM SPONSORS:
Appcelerator
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
GOLD SPONSORS:
ICEsoft
How Can AJAX Improve Homeland Security?
Isomorphic
Beyond Widgets: What a RIA Platform Should Offer
Oracle
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
SYS-CON.TV
Top Links You Must Click On


Socket Programming With Java
Socket Programming With Java

The Internet has been very popular in the past few years. With its popularity still growing, increased demand for Internet network software has grown as well. One of the greatest advantages to developing Internet software with Java is in its robust networking support built into the core language. The java.net package provides us with classes representing URLs, URL connections and sockets. Combined with the java.io package, we can quite easily write sophisticated platform-independent networking (Internet) applications.

The URL Classes provided by Java have a great amount of functionality. In many cases, it is not necessary to explicitly use sockets in Java programming because the URL classes provide socket connections in the background for you. However, there are times when Socket Objects make the most sense to use in specific applications.

One of the questions that I am asked quite frequently is, "What is a Socket?" This is a great place to start. The technical definition of a Socket is: Sockets are the end-points of a connection between two computers. A more concrete example of Sockets can be learned from your basic 7 year old. Remember that game you played where you took two paper cups and tied them together with a length of string to form a telephone. Your friend would take one of the cups and walk to the other side of the room and talk into the cup. You would put your ear up to the other cup and be able to hear your friend. The Dixie cups in this example represent Sockets. You communicate with your friend by talking into the cup (getting an output stream from the Socket and sending bytes) and by putting your ear up to the cup to hear your friend talk (getting an input stream from the Socket and reading data from it). Sockets are used quite frequently in Java Web applications.

Have you ever wondered how the World Wide Web works? We pull up a Web Browser on the client machine and type in a URL. Now, the URL represents the address of another computer on the Internet. That other computer is known as an HTTP Web Server. The server is like a switchboard that listens for a connection request on port 80. Web servers written in Java do this by using an object known as a ServerSocket object. This object's job is to listen for a connection request on a specific port. Upon receiving a connection request, the ServerSocket creates a Socket object for the Server side in order to complete the connection. Going back to the previous example, a ServerSocket object is like a person who has a stack of paper cups, waiting to play. Whenever someone requests to play our telephone game, the ServerSocket attaches the cup to a string given to it by that person.

First, let's examine a typical interaction between a Browser and a Server. A Web Browser requests a file from the server like this:

  • First a Socket connection on port 80 is opened to the HTTP Server as mentioned above.
  • Then the browser establishes input and output streams to the Server.
  • The browser's input stream becomes the server's output stream and visa-versa.
  • Next, the browser sends a request to the server using the GET command.

    GET /filename HTTP/1.0 \r\n\r\n

  • Now the browser will read the requested data from the server via its input stream.

    Let's go through the basics of writing Socket-based programs in Java. The first order of business is to create a Socket Object (see Listing 1).

    Notice that we needed to create the socket in a try block and catch the UnknownHostException and the IOExecption if there were any problems in creating the socket. After we create a Socket object, we need to establish input and output streams for the socket. We do this with two methods provided by the Socket class : getInputStream() and getOutputStream() (see Listing 2).

    Once we have the streams, we can read from and write to them just as we would any other data source.

    When we are finished using the socket, we need to close it. We close the socket as shown in Listing 3.

    Those are the basics of Socket programming with Java. To recap the steps:
    1. Create a Socket object in a try block.
    2. Establish Input and Output streams in a try block.
    3. Use the streams for communication.
    4. Close the Socket in a try block when you are finished using it.

    Security with Sockets and Applets
    An Applet can only open a connection to the same computer that the Applet was downloaded from. This means that the only computer you will be able to open a Socket to in an Applet is the Host machine from which the Applet was downloaded. Java Applications do not have this restriction.

    Writing a Client-Side Application
    With this background information, let us write a Client-Side Java application using Sockets that connects to a Web server. Upon completing a Socket connection, we will request a Web page and then display the HTML code in a text area. Please refer to the source code for SocketClient.java for a step-by-step analysis.

    First we have to import the awt, io and net class library packages. The class, SocketClient, extends Frame and implements the Runnable interface. We need a Frame Window object to contain the program because we wish to use the AWT in an application. The Runnable interface is implemented so that we can use this object with a thread.

    The constructor sets up the various window GUI components. We then create a new Thread and feed it the application as the Runnable object. We will get into the thread's purpose later. Next, we resize the window and show it to our viewing audience. That's all for the constructor of this class.

    The next method is the handleEvent(Event e) method. This method will handle three events:

  • The user presses the "Get the file" button.
  • The user presses the "Stop" button.
  • The user exits the program.

    If the "Get the file" button was pressed, we first want to stop whatever else we were doing so that we can get the file. Next, we need to see if the user actually entered a file name. If not, we will use index.html as a default file name. We then display a message in the window so that the user knows that we are connecting to the server that they have specified. Next, we create a new thread and start it. We then return true. When we started the thread, the run() method is invoked for the thread's Runnable object. We will use this run() method to do the work for us.

    If the "Stop" button is pressed, we just stop the thread and return true after displaying a message for the user. The last event we handle here is if the user exits the program. We look for a WINDOW_DESTROY event as our signal to exit the program.

    Notice how we are returning super.handleEvent(e). If we do not handle the event, it is a good idea to pass it along up the chain to our parents. The super keyword calls the parent class to handle the event. That concludes our event handling portion of this program.

    Now let's analyze the run() method. This is where the real work gets done. Before we get into it, notice a single try block embedded within the run() method! If we look at the end, we notice a single catch block for all of the exceptions. I mentioned earlier that we need to catch several different types of exceptions for these various statements in this method. However, since most of the code in this method has to be tried and caught, we do not lose any noticeable efficiency in trying the whole method like this. Also, since UnknownHostException and IOException are derived from Exception, we only really need to catch an Exception Object. The rule here is UnknownHostException IS-A Exception. This is a handy technique to remember.

    First, we create the Socket object to the specified server on port 80. After the connection is complete, we establish the streams. I have combined a few steps into two lines of code. Since I personally like DataInputStream and DataOutputStream, I created those by feeding their constructors the streams returned by Socket's getInputStream() and getOutputStream() methods.

    At this point, we can request a file. We create a request string and write it to the DataOutputStream after displaying it in the window for the user. Remember to flush() the output stream to make sure the whole message is sent to the server. With the request sent, we can now read the DataInputStream for the requested file. We read this stream just like any other data source. We read a line at a time until we reach the end of the file and store it in a string buffer. When we are finished reading the data, we display it in the window for the user to see. To finish off, we close the socket connection.

    The thread was needed here so that the run method could execute in sort of a multi-tasking fashion. We want to be able to interrupt with the stop button just like we would in a browser. Since we need a way to interrupt the process of downloading a HTML file or a stuck connection, a thread makes things run smoothly.

    Since this is an application, we need the public static void main(String[] args) method. Here, we just create this object to get things rolling.

    Conclusion
    That's it! You now know how to write a Socket Based Client Program using Java. As an interesting experiment, try to write a similar program using the URL class to do the same thing. Here is where the people who created these java.net libraries are greatly appreciated.

    import java.awt.*;
    import java.io.*;
    import java.net.*;

    This SocketClient application was written for educational purposes. It teaches you how to write a Socket Based Client Program in Javaª. This program opens a socket to a Web server on the Internet running on Port 80. It requests a HTML page and displays its source HTML code in a Text Area.

    This same method of Socket manipulation can be used to write any Client Socket-Based Application. Just change the port number to that of your server program.

    About Joseph DiBella
    Joseph M. DiBella is the Senior Java Instructor and Curiculum Developer for Computer Educational Services in New York City. He also is the President of HMJ Electronics, a computer consulting company which develops software and Java-enhanced Web sites.

  • In order to post a comment you need to be registered and logged in.

    Register | Sign-in

    Reader Feedback: Page 1 of 1

    Enterprise Open Source Magazine Latest Stories . . .
    Apache Deltacloud, the Red Hat-contributed ReSTful API that abstracts differences between clouds so services on any cloud can be managed – provided of course there’s a driver – has graduated from the Apache Foundation’s incubator and is now a full-fledged Top-Level Project (TLP). The...
    With Cloud Expo 2012 New York (10th Cloud Expo) just four months away, what better time to start introducing you in greater detail to the distinguished individuals in our incredible Speaker Faculty for the technical and strategy sessions at the conference... We have technical and st...
    AMD said late Tuesday that its chief sales officer Emilio Ghilardi had left the company and that CEO and president Rory Read is going to do his job while a replacement is sought. AMD didn’t say why Ghilardi left but it’s assumed Read wants his own people. Read is relatively new to th...
    During the lifespan of M3 (Monitis Monitor Manager) there has always been something lacking – timers. M3 execution procedure was outlined in this previous article. The execution mentioned in the latter was a one-time-execution, whereas server monitoring requires periodic invocati...
    Red Hat is putting its bought-in Gluster scale-out NAS storage technology, acquired in October, on the Amazon cloud. It’s styled Red Hat Virtual Storage Appliance for Amazon Web Services and other clouds are supposed to follow in short order.
    A new episode of the screencast series is now available at the OpenNebula YouTube Channel. This screencast demonstrates the new easily-customizable self-service portal for cloud consumers. Its aim is to offer a simplified access to shared infrastructure for non-IT end users. The scree...
    Subscribe to the World's Most Powerful Newsletters
    Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
    Click to Add our RSS Feeds to the Service of Your Choice:
    Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
    myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
    Publish Your Article! Please send it to editorial(at)sys-con.com!

    Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


    SYS-CON Featured Whitepapers
    ADS BY GOOGLE