Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

JVM Languages

Networking with Java


Web Development: Networking With Java

Networking with Java

Client/server development using the java.net package

Anil Hemrajani

Anil currently provides software engineering and training consulting services to a Fortune 500 corporation in McLean, VA. He can be contacted at [email protected] or via http:// www.patriot.net/users/anil/.


Conceptually, programming for the Internet is fairly simple: You have two processes that communicate with each other via sockets and exchange data using a certain protocol. One of these two processes can generally be identified as a client and the other as the server. One example of an Internet client/server paradigm is the combination of a web-browser client and a web server using HTTP to exchange data with each other.

Server applications such as HTTP usually listen to an assigned port on a host machine for incoming requests from clients. Upon satisfying a request, the server goes back to listening to its designated port to process the next request from a client. Clients connect to the server by specifying a host name (or an IP address) and an optional port number that the server is listening to on that host (HTTP servers generally listen to port 80 on a host).

Java provides the necessary tools for developing client and server applications for the Internet. All the classes you need for communications over the Internet are provided in the java.net package (class library). java.net comes bundled with classes for socket programming, datagrams, and helper classes that represent Internet addresses and URLs. Some of these classes include ServerSocket, Socket, DatagramPacket, DatagramSocket, InetAddress, URL, and URLConnection.

Sockets

Socket programming is conceptually similar to programming with files: You open a connection to a socket, read and/or write to it using streams of bytes, and close the connection when done. Although socket programming is more dynamic in nature than file programming (because it involves communication between two independent processes), both generally require reading and/or writing data in some form or another.

Java provides two platform-independent classes for socket communication, Socket and ServerSocket, which can be used to develop client and server applications. Data is exchanged between the client and server application using input and output streams of bytes. Once a connection is established, a new Socket object is constructed, which provides input and output streams to the socket on the other end of the two-way socket connection.

Figure 1 is a client application that uses sockets to send SQL queries to a server application and receive results from it. Listings One and Two provide the source code for both applications. Figure 2 describes how these two applications interact. Basically, the client applet/application (javaSQL) sends SQL queries to an intermediate server application (javaSQLd) which, in turn, queries a database and forwards the query results back to the client. The protocol used by these two applications is simple: The client sends five parameters (server, user, password, database, and SQL statement) as tokens separated by the "|" character (see Example 1) with "\0" at the end of the data to mark the end of input; the server simply sends back the query results.

The socket-related source code in the client and server applications is similar. The main difference is in how a Socket object is constructed on each side. On the server side, two steps are required to get a

Socket object. The first step, required only once in a program, is to create a ServerSocket object with a port number to listen to; a value of "0" can be used to connect to an anonymous port. The second step is to use the accept method to accept a connection request from a client. The accept method waits (blocks) until a connection is established. Once a connection is made, a Socket object is returned by the accept method, which is essentially a reference to the socket on the client side of the two-way socket connection. It is common to put the call to the accept method in a while loop so multiple client requests can be handled (since socket connection requests are queued, multiple requests would be processed sequentially). Example 2 (from Listing Two) demonstrates this.

Clients connect to a server by creating a new Socket object with the required parameters pointing to the location of the server socket. The Socket class provides two ways of constructing a new Socket object, one by using an InetAddress object and port number, the other by using the host name and a port number. Example 3(a) (from Listing One) creates a socket connection to the javaSQLd server application using the host name and port number obtained from the screen. Once a Socket object is successfully created, an input and output stream can be obtained for receiving and sending data to the program on the other end of the socket connection (see Example 3(a)). Reading and writing to streams can be achieved by using the various forms of the read and write methods available in the java.io.InputStream and java.io.OutputStream classes. These lines let you read and write one character at a time:

int onechar; onechar = i.read(); o.write((char)onechar);

Additionally, there are other forms of Input/Output stream classes available in the java.io package that can be constructed using an existing InputStream or OutputStream object. These classes make the task of working with incoming and outgoing bytes of data slightly easier. These classes include BufferedInputStream, BufferedOutputStream, DataInputStream, DataOutputStream, FilterInputStream, and FilterOutputStream.

Datagrams

Datagram communication is an unreliable way of sending self-contained messages (datagram packets) over the network. The delivery of the packets is not guaranteed, nor is the order or contents of packets guaranteed to be the same upon arrival. However, datagrams are useful in situations where noncritical data needs to be broadcast to several clients: For example, a server application that periodically broadcasts the current date and time to clients for synchronization purposes.

Java provides two classes for datagram communication: DatagramPacket and DatagramSocket. Both classes are required by any application that needs to send and/or receive datagrams; hence, the source code for client and server datagram applications is almost identical. Listing Three is a client datagram application that communicates with the server application in Listing Four. These programs are simplethe client program (dgClient.java) sends a "Hello" string to the server program (dgServer.java) and the server responds by sending a "Hello Back" string back to the client.

In Example 4 (from Listing Three), a DatagramPacket object contains all the necessary information for sending a message over the network; that is, the contents of the message, the destination Internet address, and the port number are all embedded in the DatagramPacket object. Both the send and receive methods in the DatagramSocket class accept a DatagramPacket as a parameter. The difference is in how the DatagramPacket object is constructed for each method. For receiving, a DatagramPacket is constructed with the buffer to hold the received data and the maximum length of data to receive. For sending, the destination Internet address and port number are also required.

Internet Addresses and URLs

To connect to an Internet server application, you need the Internet address (for example, 161.107.9.87) of the host machine the application is running on, and the port number the application is listening to on that host. The InetAddress class is used to represent an Internet address. InetAddress objects are generally constructed by using the getByName static method, which accepts a string parameter pointing to a host name or an Internet address. Once an InetAddress object is constructed, it can be passed in as a parameter to other classes (Socket, for instance). Example 5(a) opens a socket connection to the HTTP server running on www.javasoft.com. Java provides the URL and URLConnection classes to work with URLs. These classes, which use sockets and HTTP as part of their underlying implementation, simplify the task of reading data from and writing data to the resources on the Internet. Additionally, many of the methods in the java.applet.Applet class accept the URL object as a parameter in order to access audio and image files from a host machine or request a Java-enabled browser to pull up a resource pointed to by a URL object, as in Example 5(b).

Listing Five is a Java program (copyURL.java) that can be used to copy the contents of a resource on the Internet to a local file. The logic of this program is simple: It constructs a URL object, gets an input stream to the URL, opens a local file for writing, then reads from the URL and writes to the local file. In Example 6(a) (from Listing Five), opening an input stream to a resource on the Internet can be accomplished by two lines of Java codeone line to create a URL object (using one of the four constructors available), and one to get a reference to the URL's input stream.

Opening an output stream to a resource referenced by a URL requires a call to the openConnection method in the URL class, which returns a URLConnection object. Alternatively, a URLConnection object can be created directly by passing in a URL object in the constructor. The URLConnection object represents an active connection to a resource on the Internet. Example 6(b) shows the first method of constructing a URLConnection object.

In addition to providing input and output streams to a resource, the URL class also provides methods to obtain information about the current URL, such as the host name and port number. The URLConnection class contains more informative methods such as getContentType, getContentLength, getHeaderField, getLastModified, getExpiration, and related methods that provide details about the contents of a resource. Example 7(a) presents two uses of these methods, while Example 7(b) is sample output generated by Example 7(a).

Interfacing with CGI Scripts

For some time now, HTML forms and CGI scripts have been used to exchange data between the client and server parts of a web application. Java programs can be written to interface with CGI scripts using the classes provided in the java.net package. CGI provides two methods for sending parameters from HTML forms to CGI scriptsGET and POST. For the GET method, a web browser sends parameters as a CGI query string appended to the URL; for the POST method, the browser sends parameters in the data block of the information sent to a web server. While a browser automatically handles the specifics of how the data is sent to the server based on the method specified in an HTML form, Java requires that you construct the parameter data and send it to the web server. Let's look at a simple CGI script example (login.sh), that requires a "User" and "Password" parameter, and see how we would simulate the GET and POST methods in Java.

Simulating the CGI GET method is easy: Create a URL object with a string containing the protocol, host name, script name, and a CGI query string; see Example 8(a). Alternatively, you can use the showDocument method in the java.applet.Applet class to request that the browser process the URL as if a user typed it in; see Example 8(b). Simulating the CGI POST method takes a little more work. Since this method requires the parameters to be passed in the data block of the information sent to a server, you have to write the parameter data to the output stream of the URLConnection object as in Example 8(c). Note that this example works with NCSA's HTTP server; other servers might require you to also send the HTTP header.

After using either the GET or POST method successfully, you can read any results sent back by the CGI script (unless the showDocument method was used) using an input stream; see Example 8(d).

Conclusion

Whether or not you have experience in Internet programming, developing client/server Internet applications in Java is straightforward. If you like network programming, Java makes accessing the resources on the World Wide Web almost as easy as accessing local files.

Example 1: Client sending queries to an intermediate server application.

// Send User
for (idx=0; idx < tUser.getText().length(); idx++)
     o.write (tUser.getText().charAt(idx));
o.write('|');


Example 2: Calling the accept method.

Socket client;
 ...
ServerSocket server = new ServerSocket(0, 10);
while (true)
{
 ...
    client  = server.accept();
    InputStream  i = client.getInputStream();
    OutputStream o = client.getOutputStream();
 ...
}


Example 3: Creating a socket connection to the javaSQLd server application.

(a)

Integer port=new Integer(tPort.getText());
Socket s =new Socket(tHost.getText(), port.intValue(), true);


(b)

OutputStream o = s.getOutputStream();
InputStream  i = s.getInputStream();


Example 4: A DatagramPacket object contains all the necessary information for sending a message.

DatagramSocket socket = new DatagramSocket(4444);
DatagramPacket packet = new DatagramPacket(Data, 6, 
InetAddress.getByName("somehost"), 5555);
socket.send(packet);

packet = new DatagramPacket(Data, 20);
socket.receive(packet);


Example 5: (a) Opening a socket connection to the HTTP server; (b) methods in the java.applet.Applet class can accept the URL object as a parameter.

(a)

InetAddress inet=InetAddress.getByName("www.javasoft.com");
Socket s = new Socket(inet, 80, true);


(b)

getAppletContext().showDocument(new URL("http://www.patriot.net/users/anil/java/javaSQL"));



Example 6: (a) Opening an input stream to a resource; (b) constructing a URLConnection object.

(a)

URL url = new URL(args[0]);
InputStream is = url.openStream();


(b)

URLConnection urlConnect = url.openConnection();

Example 7: (a) Providing input and output streams to a resource; (b) sample output generated by Example 7(a).

(a)

System.out.print("Type: " + urlC.getContentType());
Date date=new Date(urlC.getLastModified());
System.out.print(", Modified on: " + date.toLocaleString())


(b)

Type: image/gif, Modified On: Fri Mar 15 10:07:15 1996

Example 8: (a) Create a URL object with a string; (b) using the showDocument method in the java.applet.Applet class; (c) writing the parameter data to the output stream of the URLConnection object; (d) reading results sent back by the CGI script.

(a)

URL url  = new URL("http://www.somehost.com/cgi-bin/login.sh?User
          =anil&Password=letmein");
URLConnection urlC = url.openConnection();


(b)

getAppletContext().showDocument(new URL("http://www.somehost.com/cgi-bin/
          login.sh?User=anil&Password=letmein"));


(c)

URL url = new URL("http://www.somehost.com/cgi-bin/login.sh");
urlC = url.openConnection();

urlC.setDoOutput(true);
DataOutputStream dos =
     new DataOutputStream(urlC.getOutputStream());
dos.writeBytes("User=anil&Password=letmein");
dos.writeBytes("\r\n");


(d)

int oneChar;
InputStream is = urlC.getInputStream();
while ((oneChar=is.read()) != -1)
     System.out.print((char)oneChar);

Figure 1: javaSQL and javaSQLd.

Figure 2: How javaSQL and javaSQLd interact.

Listing One

///////////////////////////////////////////////////////
// Program: javaSQL.java
// Author: Anil Hemrajani -- [email protected]
// Purpose: JavaSQL Application/Applet
///////////////////////////////////////////////////////

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


/**************************************************************************
 * "javaSQL" is the main class which provides a Java Applet/Application.
 * It creates all the necessary components (TextArea/Edit, Push Buttons)
 * to perform free-form SQL queries.
 * This class operates in 2 modes: demo and other.  In demo mode, it loads
 * data from file "demo.dat".  In other/normal mode, it communicates with
 * the "javaSQLd" server/daemon by sending it SQL and getting results back.
 * The communication is accomplished via Java sockets.
 **************************************************************************/
public class javaSQL extends java.applet.Applet
{
   TextArea   taSQL, taResults;
   TextField  tHost, tPort, tServer, tDatabase, tUser, tPassword;
   String     EXECUTE="Execute", EXIT="Exit";
   Label      statusBar;
   boolean    inAnApplet=true;
   Properties properties;
   String     propertyFile="javaSQL.ini",
              readyMsg="To query, enter SQL statement and click on Execute.";
   boolean    inDemoMode=false;

   // Send SQL to javaSQLd and receive results
   private void executeSQL()
   {
      try {
            if (inDemoMode)
            {
                showDemoData();
                return;
            }
            if (tHost.getText().trim().length()   < 1 ||
                tPort.getText().trim().length()   < 1 ||
                tServer.getText().trim().length() < 1 ||
                tUser.getText().trim().length()   < 1)
            {
                statusMsg("Please specify Host, Port, Server and User.");
                return;
            }
            Integer port=new Integer(tPort.getText());
            Socket    s =new Socket(tHost.getText(), port.intValue(), true); 

            OutputStream o = s.getOutputStream();
            InputStream  i = s.getInputStream();

            int idx;
            // Send Server
            for (idx=0; idx < tServer.getText().length(); idx++)
                 o.write (tServer.getText().charAt(idx));
            o.write('|');
            // Send User
            for (idx=0; idx < tUser.getText().length();
                 idx++)
                 o.write (tUser.getText().charAt(idx));
            o.write('|');
            // Send Password
            for (idx=0; idx < tPassword.getText().length();
                 idx++)
                 o.write (tPassword.getText().charAt(idx));
            o.write('|');
            // Send Database
            for (idx=0; idx < tDatabase.getText().length();
                 idx++)
                 o.write (tDatabase.getText().charAt(idx));
            o.write('|');
            // Send SQL
            for (idx=0; idx < taSQL.getText().length();
                 idx++)
                 o.write (taSQL.getText().charAt(idx));

            o.write('\0');
            o.flush();

            StringBuffer sb=new StringBuffer();
            int oneChar;
            while ((oneChar=i.read()) != -1)
                  sb.append((char)oneChar);
            taResults.setText(sb.toString());

            o.close();
            i.close();
          }
          catch (UnknownHostException e)
          { showCatchError(e); }
          catch (IOException e)
          { showCatchError(e); }
          finally
          {
            statusMsg(readyMsg);
          }
   }
   public void init()
   {
       // Get application icon image, play sounds, etc.
       Image iconImage;        if (inAnApplet)

       {
           String mode=getParameter("MODE");
           if (mode != null && mode.trim().toLowerCase().equals("demo"))
               inDemoMode=true;

           iconImage=getImage(getCodeBase(), "javaSQL.gif");
           play(getCodeBase(), "javaSQL.au");
       }
       else
           iconImage=Toolkit.getDefaultToolkit().getImage("javaSQL.gif");
       //*** Create shared GridBag* stuff for all panels ***
       GridBagLayout gb       = new GridBagLayout();
       GridBagConstraints gbc = new GridBagConstraints();
       //*** Push Button Panel ***
       Panel buttonPanel = new Panel();
       buttonPanel.setLayout(new GridLayout(2,1));
       buttonPanel.add(new Button(EXECUTE));
       if (!inAnApplet)
           buttonPanel.add(new Button(EXIT));
       //*** Data Source Information Panel ***
       tServer   = new TextField(10);
       tDatabase = new TextField(10);
       tUser     = new TextField(10);
       tPassword = new TextField(10);
       tPassword.setEchoCharacter('*');

       Panel dbPanel = new BorderPanel();
       dbPanel.setLayout(gb);

       // Set default constraints
       gbc.weightx   = 1.0;
       gbc.weighty   = 0.0;
       gbc.ipady     = 0;
       gbc.ipadx     = 0;
       gbc.anchor    = GridBagConstraints.CENTER;
       gbc.fill      = GridBagConstraints.HORIZONTAL;
       gbc.gridwidth = GridBagConstraints.REMAINDER;

       Label l = new Label(" Data Source Information ", Label.CENTER);
       l.setFont(new Font("TimesRoman", Font.ITALIC|Font.BOLD, 14));
       gbc.ipady     = 5;
       gb.setConstraints(l, gbc);
       dbPanel.add(l);

       gbc.anchor    = GridBagConstraints.WEST;
       gbc.ipady     = 0;
       gbc.gridwidth = 4;
       l             = new Label(" User: ", Label.RIGHT);
       gb.setConstraints(l, gbc);
       dbPanel.add(l);
       gb.setConstraints(tUser, gbc);
       dbPanel.add(tUser);
        l = new Label(" Password: ", Label.RIGHT);
       gb.setConstraints(l, gbc);

       dbPanel.add(l);

       gbc.gridwidth = GridBagConstraints.REMAINDER;
       gb.setConstraints(tPassword, gbc);
       dbPanel.add(tPassword);

       gbc.gridwidth = 4;
       l             = new Label(" DataServer: ", Label.RIGHT);
       gb.setConstraints(l, gbc);
       dbPanel.add(l);

       gb.setConstraints(tServer, gbc);
       dbPanel.add(tServer);

       l = new Label(" Database: ", Label.RIGHT);
       gb.setConstraints(l, gbc);

       dbPanel.add(l);
       gbc.gridwidth = GridBagConstraints.REMAINDER;
       gb.setConstraints(tDatabase, gbc);
       dbPanel.add(tDatabase);

       //*** javaSQL Server/daemon Information Panel ***
       tHost         = new TextField(24);
       tPort         = new TextField(6);

       Panel hostPanel = new BorderPanel();
       hostPanel.setLayout(gb);

       // Set default constraints
       gbc.weightx   = 1.0;
       gbc.weighty   = 0.0;
       gbc.ipady     = 5;
       gbc.ipadx     = 0;
       gbc.anchor    = GridBagConstraints.CENTER;
       gbc.fill      = GridBagConstraints.NONE;
       gbc.gridwidth = GridBagConstraints.REMAINDER;

       l = new Label(" javaSQLd Server Information ", Label.CENTER);
       l.setFont(new Font("TimesRoman", Font.ITALIC|Font.BOLD, 14));
       gb.setConstraints(l, gbc);
       hostPanel.add(l);

       gbc.anchor    = GridBagConstraints.WEST;
       gbc.ipady     = 0;
       gbc.gridwidth = 2;
       l             = new Label(" Host: ", Label.RIGHT);
       gb.setConstraints(l, gbc);
       hostPanel.add(l);

       gbc.gridwidth = GridBagConstraints.REMAINDER;
       gb.setConstraints(tHost, gbc);        hostPanel.add(tHost);

       gbc.gridwidth = 2;

       l             = new Label(" Port: ", Label.RIGHT);
       gb.setConstraints(l, gbc);
       hostPanel.add(l);
       gbc.gridwidth = GridBagConstraints.REMAINDER;
       gbc.fill      = GridBagConstraints.NONE;
       gb.setConstraints(tPort, gbc);
       hostPanel.add(tPort);

       //*** Build Applet Panel ***
       setLayout(gb);
       // Set default constraints
       gbc.weightx   = 0.0;
       gbc.weighty   = 0.0;
       gbc.ipady     = 10;
       gbc.ipadx     = 10;
       gbc.fill      = GridBagConstraints.NONE;
       gbc.gridwidth = 2;

       //*** Application's icon image ***
       AppIcon ai    = new AppIcon(iconImage);
       gb.setConstraints(ai, gbc);
       add(ai);

       //*** Status Message ***
       statusBar     = new Label("Welcome to javaSQL. " + readyMsg,Label.LEFT);
       gbc.ipady     = 0;
       gbc.ipadx     = 0;
       gbc.gridwidth = GridBagConstraints.REMAINDER;
       gbc.weightx   = 1.0;
       gbc.fill      = GridBagConstraints.HORIZONTAL;
       gb.setConstraints(statusBar, gbc);
       add(statusBar);

       //*** Button, DB and Host Panels ***
       gbc.gridwidth = 3;
       gbc.fill      = GridBagConstraints.BOTH;
       gb.setConstraints(buttonPanel, gbc);
       add(buttonPanel);

       gbc.gridwidth = GridBagConstraints.RELATIVE;
       gb.setConstraints(dbPanel, gbc);
       add(dbPanel);

       gbc.gridwidth = GridBagConstraints.REMAINDER;
       gb.setConstraints(hostPanel, gbc);
       add(hostPanel);

       //*** SQL and Results Components ***
       l = new Label(" SQL Statement: ", Label.LEFT);
       l.setFont(new Font("TimesRoman", Font.ITALIC|Font.BOLD, 12));
       gbc.gridwidth = GridBagConstraints.REMAINDER;        gbc.ipady     = 5;
       gb.setConstraints(l, gbc);
       add(l);


       gbc.anchor    = GridBagConstraints.CENTER;
       gbc.ipady     = 0;
       gbc.weightx   = 1.0;
       gbc.weighty   = 1.0;
       taSQL         = new TextArea(10, 70);
       taSQL.setFont(new Font("Courier", Font.PLAIN, 12));
       gbc.fill      = GridBagConstraints.BOTH;
       gbc.gridwidth = GridBagConstraints.REMAINDER;

       gb.setConstraints(taSQL, gbc);
       add(taSQL);

       taResults     = new TextArea(10, 70);
       taResults.setEditable(false);
       taResults.setFont(new Font("Courier", Font.PLAIN, 12));
       gbc.gridwidth = GridBagConstraints.REMAINDER;
       gb.setConstraints(taResults, gbc);
       add(taResults);

       // Load Defaults
       loadProperties();
   }
   public boolean handleEvent(Event evt)
   {
       if (evt.id == Event.WINDOW_DESTROY)
       {
           saveProperties();
           System.exit(0);
       }
       else
       if (evt.id == Event.ACTION_EVENT)
       {
          if (evt.target instanceof Button)
          {
            String buttonLabel = (String)evt.arg;
            if (buttonLabel.equals(EXECUTE))
                executeSQL();
            else
            if (buttonLabel.equals(EXIT))
            {
                saveProperties();
                System.exit(0);
            }
          }
          taSQL.requestFocus();
          return true;
       }
       return false;
   }
   private void statusMsg(String msgText)
   {        statusBar.setText(msgText);
   }
   private void showCatchError(Throwable e)
   {
       statusMsg(e.toString());

       if (inAnApplet)
           showStatus(e.getMessage());
       else
           System.err.println(e.getMessage());
   }
   private void loadProperties()
   {
      properties=new Properties();
      try
      {
         if (inAnApplet)
         {
             URL url        = new URL(getCodeBase(), propertyFile);
             InputStream is = url.openStream();
             properties.load(url.openStream());
         }
         else
             properties.load(new FileInputStream(propertyFile));
         tHost.setText(properties.getProperty("Host", ""));
         tPort.setText(properties.getProperty("Port", ""));
         tServer.setText(properties.getProperty("Server", ""));
         tDatabase.setText(properties.getProperty("Database", ""));
         tUser.setText(properties.getProperty("User", ""));
         tPassword.requestFocus();
      }
      catch (FileNotFoundException e) {}
      catch (IOException e) {}
   }
   private void saveProperties()
   {
      if (!inAnApplet)
      {
          properties.put("Host", tHost.getText());
          properties.put("Port", tPort.getText());
          properties.put("Server", tServer.getText());
          properties.put("Database", tDatabase.getText());
          properties.put("User", tUser.getText());

          try properties.save(new FileOutputStream(propertyFile),
                                                  "javaSQL Properties");
          catch (IOException e) {}
      }
   }
   public void showDemoData()
   {
      try
      {
         int oneChar;
         StringBuffer sb;          sb=new StringBuffer();
         DataInputStream dis;
         if (inAnApplet)
         {
            URL url = new URL(getCodeBase(), "demo.dat");
            dis     = new DataInputStream(url.openStream());

         }
         else
            dis     = new DataInputStream(new FileInputStream("demo.dat"));
         taSQL.setText(dis.readLine());

         while ((oneChar=dis.read()) != -1)
            sb.append((char)oneChar);
         taResults.setText(sb.toString());
      }
      catch (MalformedURLException e)
      { showCatchError(e); }
      catch (IOException e)
      { showCatchError(e); }
   }
   public Insets insets()
   {
      return new Insets(5,5,5,5);
   }
   public void paint(Graphics g)
   {
       g.drawRect(1, 1, size().width-3, size().height-2);
   }
   static public void main(String args[])
   {
       String  localHost="";
       javaSQL js=new javaSQL();

       if (args.length > 0 && args[0].trim().toLowerCase().equals("-demo"))
           js.inDemoMode=true;
       js.inAnApplet=false;
       js.init();

       try localHost="(" + InetAddress.getLocalHost().getHostName() + ")";
       catch (UnknownHostException e) {}

       Frame f=new Frame("javaSQL " + localHost);

       f.add("Center", js);
       f.pack();
       f.show();
   }
}
//*** Provide a Panel with a border ***
class BorderPanel extends Panel
{
   public Insets insets()
   {
      return new Insets(5,5,5,5);    }
   public void paint(Graphics g)
   {
       g.drawRect(1, 1, size().width-3, size().height-2);
   }
}
//*** Draw a 32x32 image file ***

class AppIcon extends Canvas
{
   Image currImg;
   int width=32, height=32;

   public AppIcon(Image imageFile)
   {
       currImg=imageFile;
   }
   public void paint(Graphics g)
   {
       if (currImg != null)
           g.drawImage(currImg, 0, 0, width, height, getBackground(), this);
   }
   public Dimension minimumSize()
   {
       return new Dimension(width, height);
   }
   public Dimension preferredSize()
   {
       return minimumSize();
   }
}

Listing Two

/////////////////////////////////////////////////////////
// Program: javaSQLd.java
// Author: Anil Hemrajani -- [email protected]
// Purpose: Java ISQL Server/Daemon
////////////////////////////////////////////////////////

import java.io.*;
import java.net.*;
import java.util.StringTokenizer;

class javaSQLd
{
   public static void main(String args[])
   {
      Socket client;
      int onechar;

      try {
             ServerSocket server = new ServerSocket(0, 10);
             while (true)
             {                  System.out.print("Listening to port: ");
                 System.out.print(server.getLocalPort());
                 System.out.print("\n");
                 System.out.flush();

                 client  = server.accept();
                 InputStream  i = client.getInputStream();

                 OutputStream o = client.getOutputStream();
                 StringBuffer sb = new StringBuffer();

                 while (true)
                 {
                   onechar = i.read();
                   if (onechar == '\0')
                       break;
                   else
                       sb.append((char)onechar);
                 }
                 StringTokenizer st=new StringTokenizer(sb.toString(), "|\0");
                 String Server  =new String(),
                        User    =new String(),
                        Password=new String(),
                        Database=new String(),
                        SQL     =new String();
                 int token=0;
                 while (st.hasMoreTokens())
                 {
                     token++;
                     switch (token)
                     {
                        case 1: Server=st.nextToken();
                                break;
                        case 2: User=st.nextToken();
                                break;
                        case 3: Password=st.nextToken();
                                break;
                        case 4: Database=st.nextToken();
                                break;
                        case 5: SQL=st.nextToken();
                                break;
                       default: System.err.println(
                                     "More tokens received than expected");
                                break;
                     }
                 }
                 if (SQL.trim().equalsIgnoreCase("exit") ||
                     SQL.trim().equalsIgnoreCase("quit"))
                 {
                     client.close();
                     server.close();
                     System.out.println("Exit request received.");
                     System.out.flush();
                     System.exit(0);
                 }                  String dbCmd="/usr/sybase/bin/isql"
                             + " -S" + Server
                             + " -U" + User
                             + " -P" + Password;
                 Process proc=Runtime.getRuntime().exec(dbCmd);

                 // Provide input to command
                 StringBufferInputStream sbis=

                      new StringBufferInputStream(SQL);
                 OutputStream os=proc.getOutputStream();

                 while ((onechar=sbis.read()) != -1)
                       os.write((char)onechar);
                 os.write('\n');
                 os.flush();
                 os.close();

                 // Capture command's output
                 InputStream is=proc.getInputStream();
                 while ((onechar=is.read()) != -1)
                     o.write((char)onechar);
                 o.flush();
                 is.close();

                 proc.destroy();

                 i.close();
                 o.close();
                 client.close();
             }
          }
          catch (IOException e)
          {
             e.printStackTrace(System.err);
             System.err.flush();
          }
   }
}

Listing Three

/////////////////////////////////////////////////////////
// Program: dgClient.java
// Author: Anil Hemrajani -- [email protected]
// Purpose: Sample Client Datagram App
////////////////////////////////////////////////////////

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

class dgClient
{
   static public void main(String args[])
   {
      byte Data[] = new byte[20];       String sendMsg="Hello";
      sendMsg.getBytes(0, sendMsg.length(), Data, 0);

      try
      {
          // Client on port 4444, Server on 5555
          DatagramSocket socket = new DatagramSocket(4444);
          DatagramPacket packet = new DatagramPacket(Data, 6,
                                       InetAddress.getByName("hq3unxh0"),

                                       5555);
          socket.send(packet);

          packet = new DatagramPacket(Data, 20);
          socket.receive(packet);
          String received = new String(packet.getData(), 0);
          System.out.println(received);
      }
      catch(UnknownHostException e)
      { System.err.println(e.toString()); }
      catch(SocketException e)
      { System.err.println(e.toString()); }
      catch(IOException e)
      { System.err.println(e.toString()); }
   }
}

Listing Four

///////////////////////////////////////////////////////
// Program: dgServer.java
// Author: Anil Hemrajani -- [email protected]
// Purpose: Sample Server Datagram App
///////////////////////////////////////////////////////

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

class dgServer
{
   static public void main(String args[])
   {
      byte Data[] = new byte[20];

      try
      {
          // Client on port 4444, Server on 5555
          DatagramSocket socket = new DatagramSocket(5555);
          DatagramPacket packet = new DatagramPacket(Data, 20);

          socket.receive(packet);
          String received = new String(packet.getData(), 0);
          System.out.println(received);

          String sendMsg="Hello Back";
          sendMsg.getBytes(0, sendMsg.length(), Data, 0);
          packet  = new DatagramPacket(Data, 20, packet.getAddress(),
                                       packet.getPort());
          socket.send(packet);
      }
      catch(UnknownHostException e)
      { System.err.println(e.toString()); }
      catch(SocketException e)
      { System.err.println(e.toString()); }
      catch(IOException e)
      { System.err.println(e.toString()); }
   }
}

Listing Five

///////////////////////////////////////////////////////
// Program: copyURL.java
// Author: Anil Hemrajani -- [email protected]
// Purpose: URL demo Application
////////////////////////////////////////////////////////

import java.net.*;
import java.io.*;
import java.util.Date;

class copyURL
{
  public static void main(String args[])
  {
      if (args.length < 2)
      {
          System.err.println
               ("usage: java copyURL URL LocalFile");
          System.exit(1);
      }
      try
      {
          URL           url  = new URL(args[0]);
          URLConnection urlC = url.openConnection();
          // Print info about resource
          System.out.print("Type: " + urlC.getContentType());
          Date date=new Date(urlC.getLastModified());
          System.out.println(", Modified On: " + date.toLocaleString());
          System.out.flush();

          // Copy resource to local file
          InputStream is = url.openStream();
          FileOutputStream fos =
            new FileOutputStream(args[1]);
          int oneChar, count=0;

          while ((oneChar=is.read()) != -1)
          {
             fos.write(oneChar);              count++;
          }
          is.close();
          fos.close();

          System.out.println(count + " byte(s) copied");
      }
      catch (MalformedURLException e)
      { System.err.println(e.toString()); }
      catch (IOException e)

      { System.err.println(e.toString()); }
  }
}


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.