|
SYS-CON.TV Webcasts
Comments
Did you read today's front page stories & breaking news?
SYS-CON.TV
|
Top Links You Must Click On
General Java Socket Programming With Java
Socket Programming With Java
By: Joseph DiBella
Apr. 1, 1997 12:00 AM
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: GET /filename HTTP/1.0 \r\n\r\n 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:
Security with Sockets and Applets
Writing a Client-Side Application 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: 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
import java.awt.*; 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. Reader Feedback: Page 1 of 1
Enterprise Open Source Magazine Latest Stories . . .
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
|
SYS-CON Featured Whitepapers
Most Read This Week |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||