A Server Socket in Java

This section shows a simple example of creating a server socket to listen for incoming requests. We could write the server side of a simple NTP server, but let's try something a little more ambitious. It should be fairly clear at this point that HTTP is just another of the many protocols that use sockets to run over the Internet.

A web browser is a client program that sends requests through a socket to the HTTP port on a server and displays the data that the server sends back. A basic web browser can be written in a couple of hundred lines of code if you have a GUI component that renders HTML, which Java does.

A web server is a server program that waits for incoming requests on the HTTP port and acts on those to send the contents of local files back to the requestor. It can be implemented in just a few dozen lines of code.

The example here is part of the code for a web server. This is the code that opens a server socket on the http port, port 80, and listens for requests from web browsers. We echo the requests, but don't act on them.

The code is split into two classes to better show what's happening. The first class is the main program. It instantiates a server socket on port 80 (use port 1080 if you're writing the test code on a system without root access). The code then does an accept() on the server socket, waiting for client connections to come in. When one does come in, the program creates a new object to deal with that one connection and invokes its getRequest() method.

public class HTTPServer {
    public static void main(String a[]) throws Exception {
        final int httpd = 80;
        ServerSocket ssock = new ServerSocket(httpd);
        System.out.println("have opened port 80 locally");

        Socket sock = ssock.accept();
        System.out.println("client has made socket connection");

        OneConnection client = new OneConnection(sock);
        String s = client.getRequest();
    }
}

There are only two new lines of code in this server program. This line:

ServerSocket ssock = new ServerSocket(httpd);

and this line:

Socket sock = ssock.accept(); // on the server

The first line instantiates a server socket on the given port (httpd is an int with the value 80). The second line does an accept() on this server socket. It will block or wait here until some client somewhere on the net opens a connection to the same port, like this:

clientSock = new Socket("somehost", 80); // on the client

At that point, the accept() method is able to complete, and it returns a new instance of a socket to the server. The rest of this conversation will be conducted over the new socket, thus freeing up the original socket to do another accept() and wait for another client. At the client end, the socket doesn't appear to change.

In a real server, the code will loop around and accept another connection. We'll get to that. Here is the second half of the code: the OneConnection class that the main program uses to do the work for a single client request.

import java.io.*;
import java.net.*;
class OneConnection { 
    Socket sock;
    BufferedReader in = null;
    DataOutputStream out = null;

    OneConnection(Socket sock) throws Exception{
        this.sock = sock;
          in  = new BufferedReader( 
          new InputStreamReader( sock.getInputStream() ) );
          out = new DataOutputStream(sock.getOutputStream());
    }

    String getRequest() throws Exception {
        String s=null;
        while ( (s=in.readLine())!=null) {
             System.out.println("got: "+s);
        }
        return s;
    }
}

The constructor keeps a copy of the socket that leads back to the client and opens the input and output streams. Sockets always do I/O on bytes, not Unicode chars. HTTP is a line-oriented protocol. We push a BufferedReader onto the input stream so we can use the convenient readLine() method. We could equally use java.util.Scanner.create() to wrap the input stream, and then call nextLine() on the scanner object that create() returns.

If you're using a binary protocol, do everything with streams, not readers/writers. We wrap a DataOutputStream on the output side of the socket. We don't write anything in this version of the program, but we will soon develop it and start writing.

Socket protocols

The getRequest() method reads successive lines from the socket and echoes them on the server. How does it know when to stop reading lines? This is one of the tricky things with sockets—they cannot tell the difference between “end of input” and “there is more input, but it is delayed coming through the network.”

To cope with this inability to know when it's done, socket protocols use one of three approaches:

  • Have the client precede each message by a number giving the length of the following message. Or use some other indication to end transmission, such as sending a blank line or the word BYE as in SMTP.

  • Have the client close its output stream, using sock.shutDownOutput(). That causes the next read at the server end to return -1.

  • Set a timeout on the socket, using sock.setSoTimeout(int ms). With this set to a non-zero amount, a read call on the input stream will block for only this amount of time. Then it will break out of it by throwing a java.net.SocketTimeoutException, but leaving the socket still valid for further use.

The third approach, using timeouts, is the least reliable because timeouts are always too long (wasting time) or too short (missing input). HTTP uses a mixture of approaches one and two.

Running the HTTP server program

Compile the code and then run the program. Make sure you run it on a computer that is not already running a web server; otherwise it will find that it cannot claim port 80. If all is well, the program will print out:

java HTTPServer
have opened port 80 locally

then it will block, waiting for an incoming request on the port. This is exactly what a web server does: opens port 80 and waits for incoming socket connections from clients.

Here's the interesting part. You can make that connection using any web browser! Just start up your browser and direct it to the computer where you are running the Java program. You can run your browser on a different system altogether, and give it the name of the computer running the Java program. Or, if you are running everything on one computer, the name will be “localhost,” and the URL will be something like:

http://localhost/a/b/c/d.html

The rest of the URL doesn't matter since our server program doesn't (yet) do anything with the incoming request. You will see the Java server print out the message that a socket connection has been made (“got a socket”), and then print the HTTP text it receives on the socket from the browser!

got a socket
got: GET /a/b/c/d.html HTTP/1.1
got: Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*
got: Accept-Language: en-us
got: Accept-Encoding: gzip, deflate
got: User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)
got: Host: localhost
got: Connection: Keep-Alive
got:

These strings are HTTP headers. They are created by the browser to tell the server what file it has asked for, and they provide information about what kinds of formats the browser can accept back.

A couple more points to note here. First, almost all servers uses threads. That way, they can serve the client and at the same time accept further requests. We will shortly show the code to do this. Second, these dozen or so lines of server code are at the heart of every webserver. If you add a couple of routines to read whatever file the browser asks for and write it into the socket, you have written a webserver. Let's do it.

The ServerSocket API is:

public class ServerSocket {
    public ServerSocket() throws IOException;
    public ServerSocket(int) throws IOException;
    public ServerSocket(int,int) throws IOException;
    public ServerSocket(int,int,InetAddress) throws IOException;

    public Socket accept() throws java.io.IOException;
    public void close() throws java.io.IOException;
    public java.nio.channels.ServerSocketChannel getChannel();

    public void bind(SocketAddress) throws IOException;
    public void bind(SocketAddress, int) throws IOException;
    public boolean isBound();
    public InetAddress getInetAddress();
    public int getLocalPort();

    public boolean isClosed();
    public synchronized void setSoTimeout(int) throws SocketException;
    public synchronized int getSoTimeout() throws java.io.IOException;
    public static synchronized void setSocketFactory(SocketImplFactory) 
               throws IOException;
     public synchronized void setReceiveBufferSize(int) throws SocketException;
    public synchronized int getReceiveBufferSize() throws SocketException;
}

The accept() method listens for a client trying to make a connection and accepts it. It creates a fresh socket for the server end of the connection, leaving the server socket free to do more accepts.

The bind() method is used to connect an existing socket to a particular IP address and port. (This use of bind is unrelated to the DNS bind program). You use this when you want to use channels instead of streams for socket I/O.

The other methods should be clear from their names. There are other methods in the API, but these are the main ones you will use.

Debugging sockets

The little HTTPServer program we just saw can be used to help debug some server socket problems. You can see exactly what headers the browser sends you for different HTML requests. It works for other protocols too. If you make the code listen on another port, you can look at the incoming stream there.

Another debugging technique uses the telnet program to look at incoming text to a client socket. Telnet's actual purpose is to open a command shell on a remote computer. The lines you type are sent over the socket connection, and the responses sent back the same way. However, you can tell telnet to use any port. The stream that it receives on that port will be displayed in the telnet window (or command tool—Microsoft discontinued using a GUI telnet), and the things you type will be sent through the socket back to the server. The characters you type will be sent to the other end, but not echoed, however.

TELNET is just a quick and dirty debugging technique to help you see what's going on. Figure 25-4 uses telnet to see what an NTP server is sending back. Most servers will close a socket as soon as they have given you the requested information, hence the “connection lost” pop-up window. There is also a “keep-alive” option to a socket that requests the connection be retained for expected use in the very near future. This is useful for HTTP.

Figure 25-4. Debugging with telnet

image

These days you should avoid the use of telnet and FTP for their main purpose, as they send passwords “in the clear” to the remote socket. They are thus vulnerable to packet-sniffing by crackers at routers. Use SSH, the secure shell, instead. SSH can be started with options that let it do an FTP transfer.

Finally, there's a helpful website at rikers.org. You can use one of their web pages (specifically, http://rikers.org/cgi-bin/test.cgi) to see what is happening with your HTML pages. If you specify that web page as the “Action” value for an HTML form, when you press the “submit” button, the script will echo back to you everything that your form sent across. If this site goes off the net, try doing a web search for “CGI test forms”. Using an echo script makes it easy to see what is going on, and hence what you need to correct.

Getting the HTTP command

Let's add a few lines of code (in bold) to our server to extract the HTTP GET command that says what file the browser is looking for. We will develop this example by extending the OneConnection class. That way, we will add just the new code in the child class, and use the existing methods from the parent. The code in the new child class is:

class OneConnection_A extends OneConnection { 

    OneConnection_A(Socket sock) throws Exception {
        super(sock);
    }

    String getRequest() throws Exception {
        String s=null;
        while ( (s=in.readLine())!=null) {
             System.out.println("got: "+s);
             if (s.indexOf("GET") > -1) {
                 out.writeBytes("HTTP-1.0 200 OK ");
                 s = s.substring(4);
                 int i = s.indexOf(" ");
                     System.out.println("file: "+ s.substring(0, i));
                 return s.substring(0, i);
             }
        }
        return null;
    }
}

The getRequest() method now looks at incoming HTTP headers to find the one containing a GET command. When it finds it, it writes an acknowledgement back to the browser (the “200 OK” line), and extracts the filename from the GET header. The filename is the return value of the method.

The main program will need to construct the OneConnection_A object and then call its getRequest() method. From here it is a small step to actually get that file and write it into the socket.

Here's a new class that is a child of OneConnection_A; it adds a method to get the file of the given name and write it into the socket. Since it knows how big the file is, it might as well generate the HTTP header that gives that information.

class OneConnection_B extends OneConnection_A { 

    OneConnection_B(Socket sock) throws Exception {
        super(sock);
    }

    void sendFile(String fname) throws Exception {
        String where = "/tmp/" + fname;  // create dir if necessary
        if (where.indexOf("..") > -1) 
            throw new SecurityException("No access to parent dirs");
        System.out.println("looking for " + where);
        File f = new File(where);
        DataInputStream din = new DataInputStream(
                                   new FileInputStream(f) );
        int len = (int) f.length();
        byte[] buf = new byte[len];
        din.readFully(buf);
        out.writeBytes("Content-Length: " + len + " ");
        out.writeBytes("Content-Type: text/html ");
        out.write(buf);
        out.flush();
        out.close();
    }
}

The main program will need to construct the OneConnection_B object and then add a call to its sendfile method. Sendfile will serve files out of /tmp, so create that directory if you are using a Windows computer. Now that our server has the ability to return files we need to build in some security. The first few lines of the method prepend the string “/tmp/” onto the filename. The code also checks that the filename does not contain the string “..” to enter a parent directory. These two limitations together ensure that the server will only return files from your /tmp directory.

The “Content-Length” and “Content-Type” are two standard HTTP headers that help the browser deal with what you send it. The blank line tells the browser that is the end of the headers and the text that follows should be displayed.

At this point you should try compiling the code, placing a test html file in the mp directory, and then starting the server. Browse the URL localhost/tmp/example.html and check that the browser displays the output correctly.

We have completed a basic web server. That's quite an accomplishment! The next section looks at client-side sockets again, in particular how to use a socket to pull information from a web page. It then shows the same task done by a URLConnection. We then describe the class that represents IP addresses and finish the chapter by making the web server multithreaded.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.202.209