Back Contents Next


  
  FAQ
  Java Tutorial
  Questions by Topic
  Sample test
  Other Certification sites
  Certification Tips
  Exam Objectives
  Java jobs
  Java News
  About Java Prepare
   Books
  Certification Books
  SCEA Books
  Online Books
   Tutorial Topics
  Language Fundamentals
  Operator and Assignments
  Declaration and Access Control
  Classes in Java
  AWT
  Event classes
  Threads
  Layout Managers
  Collections
  Files
   Advertisements
cover
   Feedback
  Please let us know your feedback
 
StoreBusters Marketing
javaprepare.com
your tool for Java Certification
home | tutorial | questions | test 1

5.2 Connection-Oriented Protocol Classes

The second basic mechanism, or protocol, for transfering data between a client and server, the connection-oriented protocol, establishes a connection between the client and server socket before data is transmitted. The logical device used to transfer packets of data between machines is called a socket. A socket has an associated port number that is either assigned by the operating system or supplied by the program. Data is usually sent between two sockets, one associated with the client machine and one associated with the server. When the client socket sends a packet of data, the packet is accompanied with information about the client machine's network address and the port number of the client socket. The server socket specifies only the port number it is monitoring to receive data.

 

When one of the sockets sends a packet to the other, it waits to receive confirmation that the packet was successfully received. If the socket does not receive confirmation, it re-sends the packet. Packets are read from the receiving socket in the order that they were sent. The connection-oriented class hierarchy is shown in the figure below.

 

 

 

A schematic showing the mechanism for transferring data between a client and server using the connectionless protocol is shown below. The client program creates a Socket object that opens a logical connection with the server. The server program creates a ServerSocket object that will accept the connection. When the connection is made, the ServerSocket object creates a Socket object that in turn creates InputStream and OutputStream objects. The InputStream and OutputStream objects can be used to read and write byte stream data to and from the connection. It is possible for the calling application to spin off each new connection as a separate Thread, each with its own Socket object, allowing the ServerSocket to continue to listen for new connections.

 

 

 

 

 

 

 

 

 

 

 

 

5.2.1 ServerSocket Class

public class ServerSocket extends Object

 

Object

  ServerSocket

 

The ServerSocket class is used to implement the connection-oriented communication protocol. A ServerSocket object is used to listen for a connection request from a client machine. When a connection is requested, the ServerSocket object can create a Socket object to receive and transmit data through the socket.

ServerSocket() Constructor

Constructor

Syntax

ServerSocket()

public ServerSocket(int port) throws IOException

 

public ServerSocket(int port, int backlog)
  throws IOException

 

public ServerSocket(int port, int backlog,

                    InetAddress addr)

  throws IOException

 

Creates a ServerSocket object. The port that the ServerSocket object will listen to is specified. If the port is set to 0, the ServerSocket object will use any available port. The backlog is the number of connection requests that can be placed in the ServerSocket queue. The default number is 50. Once the queue is full, additional connection requests are refused and clients will receive an error. If the server machine has multiple IP addresses, the InetAddress argument can be specify which IP address will be used.

accept() Method

Method

Syntax

accept()

public Socket accept() throws IOException

 

accept() listens for a connection request and accepts the connection. When the connection is accepted, a Socket object is returned that can be used to send and receive data through the connection. Other activity is blocked until a connection is made.

close() method

Method

Syntax

close()

public void close() throws IOException

 

close() closes the socket used by the invoking ServerSocket object and releases any system resources associated with it.

Methods to Return ServerSocket Properties

Method

Syntax

getInetAddress()

public InetAddress getInetAddress()

getLocalPort()

public int getLocalPort()

getSoTimeout()

public int getSoTimeout() throws IOException

 

getInetAddress() returns an InetAddress object representing the IP address used by the invoking ServerSocket object.

 

getLocalPort() returns the port number that the invoking ServerSocket object is listening to.

 

getSoTimeout() returns the time in milliseconds that the invoking ServerSocket object will wait for a connection. A return value of 0 means that the ServerSocket object will wait indefinitely.

setSoTimeout() method

Method

Syntax

setSoTimeout()

public void setSoTimeout(int time) throws SocketException

 

setSoTimeout() is used to change the time in milliseconds that the ServerSocket will wait for a connection.

toString() Method

Method

Syntax

toString()

public String toString()

 

toString() overrides the toString() method from the Object class and returns a String representation of the invoking Socket object.

 

Example: Using ServerSocket

 

See example Using the Connection-Oriented Protocol on page 23, where a ServerSocket object is used to accept a connection from a client in a simple client-server program.

 

5.2.2 Socket Class

public class Socket extends Object

 

Object

  Socket

 

A Socket object is used to implement stream-based, connection-oriented data communication. The Socket class encapsulates a two-way communication mechanism that is connected at both ends to an IP address and port number. An InputStream and an OutputStream are associated with the Socket, to allow data to be sent to and read from the Socket using the standard methods of those classes, defined in the java.io package. (See InputStream Class in Section 4.1.7 on page 15 and OutputStream Class in Section 4.2.9 on page 36.)

Socket() Constructor

Constructor

Syntax

Socket()

public Socket(String remoteHost, int remotePort)
  throws UnknownHostException, IOException

 

public Socket(InetAddress remoteAddress, int remotePort)
  throws IOException

 

public Socket(String remoteHost, int remotePort,
              InetAddress localAddress, int localPort)
  throws IOException

 

public Socket(InetAddress remoteAddress, int remotePort,
              InetAddress localAddress, int localPort)
  throws IOException

 

Creates a Socket object. The remote port number, and remote host name or an InetAddress object, must be specified. In addition the local port number and local host name or IP address can be provided.

Buffer Size Methods

Method

Syntax

getReceiveBufferSize()

public int getReceiveBufferSize()
  throws SocketException

getSendBufferSize()

public int getSendBufferSize()
  throws SocketException

setRecieveBufferSize()

public void setReceiveBufferSize(int size)
  throws SocketException

setSendBufferSize()

public void setSendBufferSize(int size)
  throws SocketException

 

getReceiveBufferSize() and getSendBufferSize() return the size of the input and output buffers for the invoking Socket object.

 

setReceiveBufferSize() and setSendBufferSize() suggest changes to the size of the input and output buffers. The system may or may not permit these changes.

close() Method

Method

Syntax

close()

public void close() throws IOException

 

close() closes the socket associated with the invoking Socket object and releases any system resources used by the socket.

Methods that Return Socket Properties

Method

Syntax

getInetAddress()

public InetAddress getInetAddress()

getKeepAlive()

public boolean getKeepAlive() throws SocketException

getLocalAddress()

public InetAddress getLocalAddress()

getLocalPort()

public int getLocalPort()

getPort()

public int getPort()

getSoLinger()

public int getSoLinger() throws SocketException

getSoTimeout()

public int getSoTimeout() throws SocketException

getTcpNoDelay()

public boolean getTcpNoDelay() throws SocketException

 

getInetAddress() returns an InetAddress object containing the IP address of the remote host to which the invoking Socket object is connected.

 

getKeepAlive() returns true if the 'keep-alive' property of the Socket is enabled.

 

getLocalAddress() returns an InetAddress object containing the local IP address of the invoking Socket object.

 

getLocalPort() returns the local port number for the invoking Socket object.

 

getPort() returns the port number of the remote host to which the invoking Socket object is connected.

 

getSoLinger() returns the delay in milliseconds between when the close() method is invoked and the socket is closed.

 

getSoTimeout() returns the time in milliseconds the invoking Socket object will wait for an incoming packet.

 

getTcpNoDelay() returns true if Nagle's algorithm is disabled for this socket. Nagle's algorithm combines smaller packets into larger packets for increased efficiency.

Methods that Set Socket Properties

Method

Syntax

setKeepAlive()

public void setKeepAlive(boolean on)
  throws SocketException

setSoLinger()

public void setSoLinger(boolean on, int delay)
  throws SocketException

setSoTimeout()

public void setSoTimeout(int time)
  throws SocketException

setTcpNoDelay()

public void setTcpNoDelay(boolean on)
  throws SocketException

 

setKeepAlive() specifies the value of the invoking Socket object's 'keep-alive' property.

 

setSoLinger() sets the delay in milliseconds between when the close() method is invoked and the socket is closed. If the boolean on is set to false or the int delay is set to 0, the socket closes immediately.

 

setSoTimeout() specifies the time in milliseconds the invoking Socket object will wait for an incoming packet.

 

setTcpNoDelay() specifies if Nagle's algorithm is to be used for this socket. Nagle's algorithm combines smaller packets into larger packets for increased efficiency.

Stream Methods

Method

Syntax

getInputStream()

public InputStream getInputStream()
  throws IOException

getOutputStream()

public OutputStream getOutputStream()
  throws IOException

shutDownInput()

public void shutDownInput() throws IOException

shutDownOutput()

public void shutDownOutput() throws IOException

 

getInputStream() returns an InputStream object that can be used to read data from the invoking Socket object.

 

getOutputStream() returns an OutputStream object that can be used to send data through the invoking Socket object.

 

shutDownInput() shuts down the InputStream of the invoking Socket object by placing the stream at "end of stream". Any data then received is silently discarded.

 

shutDownOutput() disables the OutputStream of the invoking Socket object.

toString() Method

Method

Syntax

toString()

public String toString()

 

toString() overrides the toString() method from the Object class and returns a String representation of the invoking Socket object.

Deprecated Constructors

Constructor

Syntax

Socket()

public Socket(String remoteHost, int remotePort,
              boolean stream) throws IOException

 

public Socket(InetAddress remoteAddress, int remotePort,
              boolean stream) throws IOException

 

These two constructors were deprecated as of Java 1.1. If the boolean stream is set to false, a datagram socket is created. DatagramSocket objects should be used instead to create this type of socket.

 

Example: Using the Connection-Oriented Protocol

 

This program implements a simple client-server application. The client and server classes are contained in two separate files. When the button on the client is pressed it connects the the server, and the server returns a String object, which is then displayed on the client.

 

To run this example, open up two windows on the same machine. Run the server program in one window, and the client program in the other.

Server program

The ServerCP class sets up a connection-oriented socket to transmit a String object to a client machine.

 

A ServerSocket object is created to listen for connection requests. The accept() method waits for a connection request and returns a Socket object when the connection is completed.

 

An ObjectOutputStream object is tied to the output stream of the Socket object using the getOutputStream() method. The ObjectOutputStream object is then used to write a String object to the output stream.

 

Placing most of the code in an infinite loop allows the server to continue to listen for connection requests as long as the program is running.

 

import java.net.*;

import java.io.*;

 

public class ServerCP {

  ServerSocket serverSocket;

  int portNumber = 8888;

  Socket socket;

  String str = "Server String";

 

  ServerCP() {

 

    // Create ServerSocket to listen for connections

    try {

      serverSocket = new ServerSocket(portNumber);

    } catch (IOException se) {}

 

    // Enter infinite loop, waiting for connections

    while (true) {

      try {

 

        // Wait for client to connnect, then get Socket

        socket = serverSocket.accept();

 

        // Use ObjectOutputStream to send String to the client

        ObjectOutputStream oos =

          new ObjectOutputStream(socket.getOutputStream());

 

        oos.writeObject(str);

 

        oos.close();

 

        // Close Socket and go back to wait for next client

        socket.close();

      } catch (IOException ioe) {}

    }

  }

 

  public static void main(String args[]) {

    ServerCP scp = new ServerCP();

  }

}

Client program

The ClientCP class creates a graphical user interface by placing a JButton and a JLabel object on a JFrame. The JButton object is associated with an ActionListener, so that when the JButton is pressed the actionPerformed() method is called.

 

Inside the actionPerformed() method, a Socket object is created using the IP address and port number of the server. (Since both programs will be run on the same machine, the local host address is used.)

 

An ObjectInputStream object is tied to the socket input stream using the getInputStream() method. The ObjectInputStream object reads the String object from the socket stream.

 

The JLabel text is updated with the String transmitted from the server.

 

import java.net.*;

import java.io.*;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

 

public class ClientCP extends JFrame implements ActionListener {

  Socket socket;

  int portNumber = 8888;

  JButton button;

  JLabel lblName;

  String str = "";

  JPanel p1, p2;

 

  public ClientCP() {

 

    // Create user interface components

    button = new JButton("download");

    button.setFont(new Font("Serif", Font.PLAIN, 12));

    button.setBorder(BorderFactory.createRaisedBevelBorder());

    button.addActionListener(this);

 

    lblName = new JLabel("");

    lblName.setForeground(Color.black);

    lblName.setFont(new Font("Serif", Font.PLAIN, 12));

 

    p1 = new JPanel();

    p1.add(lblName);

 

    p2 = new JPanel();

    p2.add(button);

 

    getContentPane().add(p2, BorderLayout.NORTH);

    getContentPane().add(p1, BorderLayout.CENTER);

 

    addWindowListener(new WinClosing());

    setBounds(100, 100, 300, 300);

    setVisible(true);

  }

 

  public void actionPerformed(ActionEvent ae) {

    // Called when the button is pressed

 

    // Create a socket connection to the specified machine and

    // port number

    try {

      socket = new Socket(InetAddress.getLocalHost(),

                          portNumber);

    } catch (IOException se) {}

 

    // Use ObjectInputStream to convert input from server to a

    // String object

    try {

      ObjectInputStream ois =

        new ObjectInputStream(socket.getInputStream());

      try {

        str = (String) ois.readObject();

      } catch (ClassNotFoundException ce) {}

    } catch (IOException ioe) {}

 

    // Display the string on the user interface

    lblName.setText(str);

    p1.revalidate();

  }

 

  public static void main(String args[]) {

    ClientCP cp = new ClientCP();

  }

}

 

class WinClosing extends WindowAdapter {

  public void windowClosing(WindowEvent we) {

    System.exit(0);

  }

}

Output

The user interface of the client program is shown below. After pressing the download button, the information obtained from the server (the string Server String) is displayed.

 

 

 


 


BackContentsNext
©1999 Wrox Press Limited, US and UK.
home | tutorial | questions | test 1