Welcome!

Java Authors: Liz McMillan, Walter H. Pinson, III, Maureen O'Gara, Yakov Werde, Tony Bishop

Related Topics: Java

Java: Article

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.

  • More Stories By 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.

    Comments (0)

    Share your thoughts on this story.

    Add your comment
    You must be signed in to add a comment. Sign-in | Register

    In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.