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


References

Dr. Vinge's Java Networking lecture, Spring 2000, http://www-rohan.sdsu.edu/faculty/vinge/courses/spring00/cs580/notes/javanet/javanet.html

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

Java.net.Socket, JDK 1.3, http://java.sun.com/j2se/1.3/docs/api/java/net/Socket.html


Doc 7, Simple Java Client Slide # 2

Building a Connection


Transport layer association is uniquely defined by the following:


Identify the parts:

    $ telnet sdsu.edu 13
    Trying 130.191.229.14...
    Connected to sdsu.edu.
    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:

Information
Data from example
protocol
TCP (implied by the telnet program)
name of the server machine
sdsu.edu
port number on the server machine
13


The missing parts:

Information
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

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

Doc 7, Simple Java Client Slide # 5

java.net.Socket


Several constructors:

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

The constructor builds the connection

Exceptions thrown by the constructors:

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



Doc 7, Simple Java Client Slide # 6

java.net.Socket 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)


On UNIX:

Standard UNIX DNS software
Program that provides the DNS service

DNS

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 java.net.InetAddress

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
import java.net.InetAddress; 
import java.net.InetAddress;
import java.io.*;
class SimpleDNS {
   
   public static void main(String[] args)  {
      String   hostName;
      if ( args.length != 1 ) {
         System.out.println("Usage: java SimpleDNS hostName");
         System.exit(1);
      }
      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) + " " );
         }
         System.out.println();
      } catch (IOException DNSerror) {
         System.err.println(DNSerror);
         System.exit(1);
      }
   }
}


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

$ java SimpleDNS www.sdsu.edu
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
PortScanner
From Java Network Programming chapter 10

import java.net.*;
import java.io.*;
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

TCP_NODELAY


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

SO_LINGER


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

SO_TIMEOUT


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.

SO_TIMEOUT

An InterruptedException is thrown when time out occurs

Socket is still connected and usable


Doc 7, Simple Java Client Slide # 16

SO_RCVBUF & SO_SNDBUF


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


SO_KEEPALIVE


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