CS 580 Client-Server Programming Fall Semester, 2000 Java Server Intro |
||
---|---|---|
© 2000, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 04-Sep-00 |
What is a Server?
Server
while (true) { Wait for an incoming request; Perform whatever actions are requested; }
Some Basic Server Issues
Java TCP Sockets
ServerSocket basic methods
public ServerSocket(int port) //port = 0 gives random port
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
A Simple Server
import java.net.Socket; import java.net.ServerSocket; import java.io.*; 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(); processRequest( client.getInputStream(), client.getOutputStream()); client.close(); } }
(Why "new ServerSocket(0)"?)
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(); parsedOutput.println(now.toString()); } } }
Note: This server is just a first example. It needs a lot of work. We will be working on improving it in later lectures.
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
Trying 130.191.3.100...
Connected to rohan.sdsu.edu.
Escape character is '^]'.
date today
Mon Sep 04 13:37:30 PDT 2000
Connection closed by foreign host.
rohan 18-> telnet rohan 62047
Trying 130.191.3.100...
Connected to rohan.sdsu.edu.
Escape character is '^]'.
time
Connection closed by foreign host.
In this class, shut things down:
rohan 19-> fg
java SimpleDateServer
^C
Simple Server Issues
Client A builds connection to server, Client A goes to lunch Client B builds connection to server and ... :-(