SDSU CS 580 Client-Server Programming
Fall Semester, 2002
Server Intro
Previous    Lecture Notes Index    Next    
© 2002, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 26-Sep-02

Contents of Doc 10, Server Intro


Java Network Programming, Harold

VisualWorks Internet Client Developer's Guide & Socket. See

Doc 10, Server Intro Slide # 2
Reading AssignmentJava
Java Network Programming, Harold

Basic Network Concepts, Chapter 2
If you are not familiar with basic networking

Java I/O Chapter 4
If you are weak on Streams, Readers and Writers

Sockets for Servers Chapter 11


Internet Client Developer's Guide, Socket Programming Chapter 2.

Internet Client Developer's Guide is doc/NetClientDevGuide.pdf in the VisualWorks 7 installation

Doc 10, Server Intro Slide # 3

What is a Server?


Any program that waits for incoming communication requests from a client
Extracts requested information from data and return to client

Basic algorithm:

   while (true) {
     Wait for an incoming request;
     Perform whatever actions are requested;

Doc 10, Server Intro Slide # 4
Example - Echo Server

| server |
server := SocketAccessor newTCPserverAtPort: 9009.
server listenFor: 5.
 [ | acceptedSocket |
   "wait for a new connection"
   acceptedSocket := server accept.
   "fork off processing of the new stream socket"
   [ | stream char |
      stream := acceptedSocket readAppendStream.
      stream lineEndTransparent.
      [ (char := stream next) isNil ] whileFalse: [
         stream nextPut: char; commit ].
      stream close. 
   ] forkAt: Processor userSchedulingPriority -1.
] repeat. 

Doc 10, Server Intro Slide # 5
Some Basic Server Issues

Doc 10, Server Intro Slide # 6


Streams verses Buffers

Both Java & Smalltalk provide access to socket data via

Stream access is easier

Buffer access can be faster

We will cover Stream access first

Doc 10, Server Intro Slide # 7

Java TCP Sockets

Main Classes
Used by servers to listen for clients
Used by clients to talk to servers
Used by servers to talk to clients
ServerSocket basic methods

public ServerSocket(int port) //port = 0 gives random port
public ServerSocket(int port, int backlog)
public ServerSocket(int port, int backlog, InetAddress bindAddress)
public Socket accept() throws IOException
public void close() throws IOException
public int getLocalPort()

Socket basic methods

public InputStream getInputStream() throws IOException
public OutputStream getOutputStream() throws IOException

Doc 10, Server Intro Slide # 8

A Simple Date Server

import java.util.Date;
class SimpleDateServer {

   public static void main(String[] args) throws IOException {
      ServerSocket acceptor = new ServerSocket(0);
      System.out.println("On port " + acceptor.getLocalPort());
      while (true) {
         Socket client = acceptor.accept();

(Why "new ServerSocket(0)"?)

Doc 10, Server Intro Slide # 9
Processing Client Request

   static void processRequest(InputStream in,OutputStream out)
      throws IOException {
      BufferedReader parsedInput = 
            new BufferedReader(new InputStreamReader(in));
      // the "true" is to get autoflushing:
      PrintWriter parsedOutput = new PrintWriter(out,true);
      String inputLine = parsedInput.readLine();
      if (inputLine.startsWith("date")) {
         Date now = new Date();

Note: This server is just a first example. It needs a lot of work. We will be working on improving it in later lectures.

Doc 10, Server Intro Slide # 10
Running the Server

Sample run of SimpleDateServer.
(I typed everything appearing in bold font here.)

rohan 16-> java SimpleDateServer &
[1] 16269
On port 62047

rohan 17-> telnet rohan 62047
Connected to
Escape character is '^]'.
date today
Mon Sep 04 13:37:30 PDT 2000
Connection closed by foreign host.

rohan 18-> telnet rohan 62047
Connected to
Escape character is '^]'.
Connection closed by foreign host.

In this class, shut things down:

rohan 19-> fg
java SimpleDateServer

Doc 10, Server Intro Slide # 11
Warning About telnet Usage

Using telnet to interact with a server is

Don’t design server assuming it interacts directly with a human!

Doc 10, Server Intro Slide # 12

Smalltalk TCP Sockets

Main Classes

Represents an IP address for a machine
Socket connection for server & client

SocketAccessor creation methods

newTCP            “selects random port”
newTCPserverAtPort: portNumber

SocketAccessor instance methods

   Wait for a client connection and return it
   return any waiting client connection, 
   return nil if no waiting client connections
   Return a stream of the given type on the conection

Doc 10, Server Intro Slide # 13

A Simple Date Server

Smalltalk defineClass: #SimpleDateServer
   superclass: #{Core.Object}
   indexedType: #none
   private: false
   instanceVariableNames: 'serverSocket '
   classInstanceVariableNames: ''
   imports: ''
   category: 'SimpleServer'

SimpleDateServer class methodsFor: 'instance creation'

port: anInteger
   ^super new setPort: anInteger 

Doc 10, Server Intro Slide # 14
SimpleDateServer instance methods

setPort: anInteger 
   serverSocket := SocketAccessor newTCPserverAtPort: anInteger.
      listenFor: 4;
      soReuseaddr: true 

   | childSocket clientConnection clientIOStream |
   [childSocket := serverSocket accept.
   clientIOStream := childSocket readAppendStream.
   clientIOStream lineEndTransparent.
   self processRequestOn: clientIOStream.] repeat

processRequestOn: anReadAppendStream 
   | clientRequest |
   clientRequest := anReadAppendStream through: Character cr.
   (clientRequest startsWith: 'date') 
      ifTrue: [anReadAppendStream nextPutAll: 
                  Time dateAndTimeNow printString].
   anReadAppendStream close
Running the Server

server := SimpleDateServer port: 5556.
serverProcess := [server run] fork

Doc 10, Server Intro Slide # 15

Simple Server Issues

Using our SimpleDateServer

      Client A builds connection to server, 
      Client A goes to lunch 
      Client B builds connection to server and ... :-( 

Multiple connections need to be accepted concurrently.

Doc 10, Server Intro Slide # 16


TCP accepts connections before the server is ready

TCP keeps a backlog queue of connections server has not accepted

Java ServerSocket constructor

SocketAccessor>>listenFor: aNumber

There is no reasonable way to find out:

Backlog Experiment

Start the SimpleDateServer

Connect to the server using telnet

While the server is waiting for you to type something

Connect to the server with a second telnet session

In the second session type “date” and return

What happens?

Now type “date” and return in the first session

What happens?

Doc 10, Server Intro Slide # 17

Multi-homed Machines

Some machines have two or more physical network interface

Each network interface has its own IP address
public ServerSocket(int port)
Listens to the give port on all IP addresses for the machine
public ServerSocket(int port, int backlog, InetAddress bindAddress)

Listens to the give port only on the one IP address

Doc 10, Server Intro Slide # 18

Reusing a Port

Closing TCP connections can remain for several minutes

TCP may block use of the port until the connection is gone

This can be annoying in development

SocketAccessor>> soReuseaddr: true

ServerSocket method setReuseAddress(boolean on)

   Allows the port to be resued

Doc 10, Server Intro Slide # 19

End of Line

End of Line Convention
Line Feed (LF)
Carriage return (CR)

LF is ASCII character 10

CR is ASCII character 13

A server should not make assumptions about a client’s platform

A client should not make assumptions about a server’s platform

Client-server protocol should specify which characters are used

Doc 10, Server Intro Slide # 20
End of Line & Smalltalk

Java and Smalltalk programs run on all major platforms

Smalltalk assumes files use platform’s end of line convention

Smalltalk input streams convert platforms end of line to CR

Smalltalk output streams convert CR to platform’s end of line

This makes writing cross platform programs easier

Don’t want this to happen socket streams

BufferedExternalStream>> lineEndTransparent

   Turns off converstion between CR & end of line

How does Java handle this?

Doc 10, Server Intro Slide # 21

End of File

On a stream connected to a socket

End of file indicates that the connection has been closed!

Don’t use end of file to determine when other end is done talking!

Doc 10, Server Intro Slide # 22

End of Message

How do we know when we are at the end of a message?

BufferedReader parsedInput = 
      new BufferedReader(new InputStreamReader(in));

char[] message = new char[500];
int sizeRead =, 0, 500);

We still may not have the entire message!


Doc 10, Server Intro Slide # 23
End of Message

A good client-server protocol specifies

Main methods used:

Doc 10, Server Intro Slide # 24


Java & Smalltalk streams are buffered

TCP buffers output before sending

A server cannot read bytes left in a client’s buffer


   Sends data in stream to OS

PrintWriter flush();

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

Previous    visitors since 26-Sep-02    Next