Home > Articles > Programming > Java

Networking in Java

This chapter is from the book

This chapter is from the book

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.

Security of Network Programs—A Cautionary Tale!

Be very careful when you start developing networked programs on your computer. Before you try it at work, check if there is a company policy about network use. You can get fired for doing the wrong thing!

The problem is that any server sockets you create may be visible more widely than you intended. If you are running this at home, and you are not using a firewall, your server socket will be visible to the entire net. That's like leaving the front door of your home wide open.

When I was developing the HTTP server in Java for this chapter, I left it running on my PC to test it. Someone's automated port scanner script soon noticed my server, made an unauthorized connection to it, and issued this HTTP command:

GET /scripts/..%%35c../winnt/system32/cmd.exe?/c+dir HTTP/1.0

This is an attempt to break out of the scripts directory, run a shell, and do a "dir" to see what's on my system. Crackers will try to add their own backdoor on your computer where you'll never find it. Then they can use your system whenever it's on the net (they love cable modems) for such things as distributed denial of service attacks. My server was logging client requests, but not fulfilling them, so the nimrod was out of luck. But be careful out there; people are actively looking for systems to break into.

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 on a Unix 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. DataInputStream has one of those too, but it is deprecated.

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.

  • 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 webserver does: opens port 80 and waits for incoming socket connections from clients.

Loopback Address

<Anchor1>Every computer system on the Internet has a unique IP address consisting of four groups of digits separated by periods like this:

They are currently revising and increasing the IP address specification so that there will be enough new IP addresses to give one to every conceivable embedded processor on earth, and a few nearby friendly planets. These version 6 addresses look like: 1080:0:0:0:8:800:200C:417A

One special version 4 IP address is: This is the "loopback" address used in testing and debugging. If a computer sends a packet to this address, it is routed to itself, without actually leaving the system. Thus, this special address can be used to run Internet software even if you are not connected to the Internet. Set your system up so that the Internet services it will be requesting are all at the loopback address. Make sure your system is actually running the demons corresponding to the services you want to use.

The hostname for the loopback address is "localhost," if you are requesting services by name rather than IP address. On any system, you should be able to enter the command "ping localhost" and have it echo a reply from the loopback IP address. If you can't do this, it indicates that your TCP/IP stack is not set up properly.

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:


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

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 format 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. You would use this when you want to use channels instead of streams for socket I/O; there's an example at the end of the chapter.

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.

Standing on the Corner, Watching All the Packets Go By

The server program, shown on the previous pages, will echo all the input that is sent to one socket. This is similar to the way that the FBI's controversial Carnivore program works.

Carnivore was created so that the FBI could do the online equivalent of phone tapping. It works at the more fundamental level of individual packets rather than sockets, but the principle is the same.

Carnivore is basically a packet sniffer that can be installed at an ISP and directed to copy packets that meet certain criteria (to or from a given IP address, for example). In this way, Carnivore can give the FBI a copy of all the email, all the web site visits, all the telnet sessions for a particular target over the course of a month or more. A court order is needed to authorize each use of Carnivore.

The FBI made a PR error by giving the program such an aggressive name. Law enforcement needs access to these tools to track down online fraud, network disruption, and other crimes. But they would have done themselves a favor by calling the software something calmer like "Old Packet Collector."

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, 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 17–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 17–4 Debugging with Telnet.

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. There is a Java implementation of SSH on the CD that comes with this book.

Using Netstat

Another useful tool for seeing what is going on with your network connection is netstat. It is available on Windows and Unix. Run netstat like this:

c:\> netstat
Active Connections
 Proto Local Address   Foreign Address            State
 TCP   h:1891          images-vdc.amazon.com:80   ESTABLISHED
 TCP   h:1902          images-vdc.amazon.com:80   ESTABLISHED
 TCP   h:1426          afu.com:143                ESTABLISHED
 TCP   h:1025          localhost:1028             ESTABLISHED
 TCP   h:1028          localhost:1025             ESTABLISHED

This shows all the current IP connections, the local socket, the remote socket, and the state. Netstat lets you see if you can at least make a connection to a remote system.

The "-?" option to netstat will give you a message about other options.

Finally, there's a very helpful website at straylight.cso.niu.edu. You can use one of their webpages (specifically, straylight.cso.niu.edu/cgi-bin/test-cgi.cmd) 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 websearch 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 {

  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\r\n");
         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.

Never Use println() with Sockets!

The println() method is defined to output the platform specific line separator. This will be "\n" on Unix, "\r" on Macs, and "\r\n" on Windows.

However, lots of TCP/IP protocols are line based, and the line is defined to end with carriage return line feed "\r\n", or just line feed "\n". So if you're on a Mac, the println method won't output something that a socket server recognizes as a complete end of line sequence.

The Mac client will do a println, which sends a "\r", and then wait for a response from the server. The server will get the "\r" and wait for a "\n" to complete the end of line sequence. Result: deadlock! Each end is waiting for something from the other. See Apple Tech Note 1157 for more on this:


The solution is to never use println with remote protocols on any platform. Always use explicit "\r\n" characters when writing to a 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 {

  void sendFile(String fname) throws Exception {
    String where = "/tmp/" + fname;
    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];
    out.writeBytes("Content-Length: " + len + "\r\n");
    out.writeBytes("Content-Type: text/html\r\n\r\n");

The main program will need to construct the OneConnection_B object and then add a call to its send file method. 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 \tmp directory, and then starting the server. Browse the URL localhost/tmp/exam_ple.html and check that the browser displays the file correctly.

We have completed a basic webserver. 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020