SDSU CS 580 Client-Server Programming
Fall Semester, 2000
Simple Java Client
Previous    Lecture Notes Index    Next    
© 2000, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 13-Sep-00

Contents of Doc 7, Simple Java Client


Dr. Vinge's Java Networking lecture, Spring 2000,

Java Network Programming 2nd Edition, Harold, 2000, O'Reilly, Chapter 10, JDK 1.3,

Doc 7, Simple Java Client Slide # 2

Building a Connection

Transport layer association is uniquely defined by the following:

Identify the parts:

    $ telnet 13
    Connected to
    Escape character is '^]'.
    Thu Feb  3 22:30:35 2000
    Connection closed by foreign host.

Doc 7, Simple Java Client Slide # 3
IP Connecting Parts

Information a client normally needs:

Data from example
TCP (implied by the telnet program)
name of the server machine
port number on the server machine

The missing parts:

Where does it come from?
address of the local machine
Automatically retrieved from the OS
port number on the local machine
OS supplies random open port

Doc 7, Simple Java Client Slide # 4
Simple Java Client

class GetTime {
   public static void main(String[] args)  {
      String      hostName;
      Socket   client = null;
      if ( args.length != 1 ) {
         System.out.println("Usage: java GetTime hostName");
      hostName = args[0];
      try {
         client = new Socket(hostName, 13);
      } catch (UnknownHostException hostError) {
      } catch (IOException genericError) {
      try {
        BufferedReader in =
         new BufferedReader(
           new InputStreamReader(client.getInputStream()));
        String   inputLine;
        while ((inputLine = in.readLine()) != null) {
         System.out.println("Received: " + inputLine);
      } catch (IOException IOError) {

Doc 7, Simple Java Client Slide # 5

Several constructors:

   Socket(String hostname, int portNumber) 
   Socket(InetAddress hostAddress, int portNumber) 

The constructor builds the connection

Exceptions thrown by the constructors:

Reason it is raised
The specified host is not valid or cannot be looked up
Something went wrong attempting to build a connection. Most common cause is "Connection refused" - no service on the specified port

Doc 7, Simple Java Client Slide # 6 Methods

   close(  )

Terminates an existing connection.

   getInputStream(  )
   getOutputStream(  )

These two provide access to IO through the connection.

NOTE network IO is always done in packets. This may produce strange results. Solution: use the Buffered IO classes.

   getLocalPort(  )

Doc 7, Simple Java Client Slide # 7

Domain Name Service (DNS)


Standard UNIX DNS software
Program that provides the DNS service


Converts host and domain names into IP addresses
Converts IP addresses into host and domain names

Why DNS?

Doc 7, Simple Java Client Slide # 8
DNS through

Use following static methods to create InetAddress

InetAddress  getByName(String host)
InetAddress[]  getAllByName(String host)
InetAddress getLocalHost(  )
Host can be machine name or IP address

Useful methods

String getHostName(  )
byte[] getAddress(  )

Doc 7, Simple Java Client Slide # 9
InetAddress Example
class SimpleDNS {
   public static void main(String[] args)  {
      String   hostName;
      if ( args.length != 1 ) {
         System.out.println("Usage: java SimpleDNS hostName");
      hostName = args[0];
      try {
         InetAddress address = InetAddress.getByName(hostName);
         byte ip[] = address.getAddress();
         for (int octet=0; octet < ip.length; octet++) {
            System.out.print( ((int)ip[octet] & 0xff) + " " );
      } catch (IOException DNSerror) {

Doc 7, Simple Java Client Slide # 10
Running the Example

$ java SimpleDNS
130 191 13 5 

Doc 7, Simple Java Client Slide # 11

Closing Sockets

A socket is closed when:

Good practice to close socket when done with it

On a closed socket you can still get its

An exception is raised if you use a stream on a close socket

In JDK 1.3 you can close 1/2 of the socket

Doc 7, Simple Java Client Slide # 12
From Java Network Programming chapter 10

public class PortScanner  {
   public static void main( String[] args) throws IOException  {
      String host = "localhost";
      Socket connection = null;
      try  {
         for (int port = 1; port < 65536; port++)  {
            try  {
               connection = new Socket(host, port);
               System.out.println("Server on port " + port )
            catch (IOException error ) {// no server on this port 
      catch (UnknownHostException error ) {
         System.err.println( error );
      finally {
         if (connection != null ) connection.close();

Doc 7, Simple Java Client Slide # 13

Socket Options

You to change parameters controlling how native sockets send and receive data


public void setTcpNoDelay(boolean on) throws SocketException
public boolean getTcpNoDelay() throws SocketException
Disable/enable Nagle's algorithm

Exception is raised if underlying native sockets do not support this option

Doc 7, Simple Java Client Slide # 14


public void setSoLinger(boolean on, int lingerSeconds)
throws SocketException
public boolean getSoLinger() throws SocketException

What happens to waiting packets when socket is closed?

Option 1
Drop packets and close socket
Option 2
Wait N seconds to
send packets and
receive acknowledgements
lingerSeconds is number of seconds to wait

0 value = no wait

Max value is 65,535 seconds (~18 hours)

Best to use system default

Doc 7, Simple Java Client Slide # 15


public void setSoTimeout(int timeout) throws SocketException
public boolean getSoTimeout() throws SocketException
How long does read() block on a socket?

Default is to block until there is data.


An InterruptedException is thrown when time out occurs

Socket is still connected and usable

Doc 7, Simple Java Client Slide # 16


public void setReceiveBufferSize(int size) throws SocketException
public int getReceiveBufferSize()  throws SocketException

public void setSendBufferSize(int size) throws SocketException
public int getSendBufferSize() throws SocketException

Suggests the input/output buffer size used in the TCP stack


New in JDK 1.3

Have client send data on an idle connection to insure server is still alive

Default is off

Copyright ©, All rights reserved.
2000 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
OpenContent license defines the copyright on this document.

Previous    visitors since 13-Sep-00    Next