SlideShare a Scribd company logo
1 of 20
Download to read offline
1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Network Programming:
Servers
Network Programming: Servers2 www.corewebprogramming.com
Agenda
• Steps for creating a server
1. Create a ServerSocket object
2. Create a Socket object from ServerSocket
3. Create an input stream
4. Create an output stream
5. Do I/O with input and output streams
6. Close the socket
• A generic network server
• Accepting connections from browsers
• Creating an HTTP server
• Adding multithreading to an HTTP server
Network Programming: Servers3 www.corewebprogramming.com
Steps for Implementing a
Server
1. Create a ServerSocket object
ServerSocket listenSocket =
new ServerSocket(portNumber);
2. Create a Socket object from ServerSocket
while(someCondition) {
Socket server = listenSocket.accept();
doSomethingWith(server);
}
• Note that it is quite common to have
doSomethingWith spin off a separate thread
3. Create an input stream to read client input
BufferedReader in =
new BufferedReader
(new InputStreamReader(server.getInputStream()));
Network Programming: Servers4 www.corewebprogramming.com
Steps for Implementing a
Server
4. Create an output stream that can be used
to send info back to the client.
// Last arg of true means autoflush stream
// when println is called
PrintWriter out =
new PrintWriter(server.getOutputStream(), true)
5. Do I/O with input and output Streams
– Most common input: readLine
– Most common output: println
6. Close the socket when done
server.close();
– This closes the associated input and output streams.
Network Programming: Servers5 www.corewebprogramming.com
A Generic Network Server
import java.net.*;
import java.io.*;
/** A starting point for network servers. */
public class NetworkServer {
protected int port, maxConnections;
/** Build a server on specified port. It will continue
* to accept connections (passing each to
* handleConnection) until an explicit exit
* command is sent (e.g. System.exit) or the
* maximum number of connections is reached. Specify
* 0 for maxConnections if you want the server
* to run indefinitely.
*/
public NetworkServer(int port, int maxConnections) {
this.port = port;
this.maxConnections = maxConnections;
}
...
Network Programming: Servers6 www.corewebprogramming.com
A Generic Network Server
(Continued)
/** Monitor a port for connections. Each time one
* is established, pass resulting Socket to
* handleConnection.
*/
public void listen() {
int i=0;
try {
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) ||
(maxConnections == 0)) {
server = listener.accept();
handleConnection(server);
}
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
Network Programming: Servers7 www.corewebprogramming.com
A Generic Network Server
(Continued)
...
protected void handleConnection(Socket server)
throws IOException{
BufferedReader in =
SocketUtil.getBufferedReader(server);
PrintWriter out =
SocketUtil.getPrintWriter(server);
System.out.println
("Generic Network Server:n" +
"got connection from " +
server.getInetAddress().getHostName() + "n" +
"with first line '" +
in.readLine() + "'");
out.println("Generic Network Server");
server.close();
}
}
– Override handleConnection to give your server the
behavior you want.
Network Programming: Servers8 www.corewebprogramming.com
Using Network Server
public class NetworkServerTest {
public static void main(String[] args) {
int port = 8088;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
NetworkServer server = new NetworkServer(port, 1);
server.listen();
}
}
Network Programming: Servers9 www.corewebprogramming.com
Network Server: Results
• Accepting a Connection from a WWW
Browser
– Suppose the above test program is started up on port 8088
of server.com:
server> java NetworkServerTest
– Then, a standard Web browser on client.com
requests http://server.com:8088/foo/,
yielding the following back on server.com:
Generic Network Server:
got connection from client.com
with first line 'GET /foo/ HTTP/1.0'
Network Programming: Servers10 www.corewebprogramming.com
HTTP Requests and Responses
• Request
GET /~gates/ HTTP/1.0
Header1: …
Header2: …
…
HeaderN: …
Blank Line
– All request headers are
optional except for Host
(required only for HTTP/1.1
requests)
– If you send HEAD instead of
GET, the server returns the
same HTTP headers, but no
document
• Response
HTTP/1.0 200 OK
Content-Type: text/html
Header2: …
…
HeaderN: …
Blank Line
<!DOCTYPE …>
<HTML>
…
</HTML>
– All response headers are
optional except for
Content-Type
Network Programming: Servers11 www.corewebprogramming.com
A Simple HTTP Server
• Idea
1. Read all the lines sent by the browser, storing them in
an array
• Use readLine a line at a time until an empty line
– Exception: with POST requests you have to read
some extra data
2. Send an HTTP response line (e.g. "HTTP/1.0 200 OK")
3. Send a Content-Type line then a blank line
• This indicates the file type being returned
(HTML in this case)
4. Send an HTML file showing the lines that were sent
5. Close the connection
Network Programming: Servers12 www.corewebprogramming.com
EchoServer
import java.net.*;
import java.io.*;
import java.util.StringTokenizer;
/** A simple HTTP server that generates a Web page
* showing all of the data that it received from
* the Web client (usually a browser). */
public class EchoServer extends NetworkServer {
protected int maxInputLines = 25;
protected String serverName = "EchoServer 1.0";
public static void main(String[] args) {
int port = 8088;
if (args.length > 0)
port = Integer.parseInt(args[0]);
EchoServer echoServer = new EchoServer(port, 0);
echoServer.listen();
}
public EchoServer(int port, int maxConnections) {
super(port, maxConnections);
}
Network Programming: Servers13 www.corewebprogramming.com
EchoServer (Continued)
public void handleConnection(Socket server)
throws IOException{
System.out.println(serverName + ": got connection from " +
server.getInetAddress().getHostName());
BufferedReader in = SocketUtil.getBufferedReader(server);
PrintWriter out = SocketUtil.getPrintWriter(server);
String[] inputLines = new String[maxInputLines];
int i;
for (i=0; i<maxInputLines; i++) {
inputLines[i] = in.readLine();
if (inputLines[i] == null) // Client closes connection
break;
if (inputLines[i].length() == 0) { // Blank line
if (usingPost(inputLines)) {
readPostData(inputLines, i, in);
i = i + 2;
}
break;
}
}
...
Network Programming: Servers14 www.corewebprogramming.com
EchoServer (Continued)
printHeader(out);
for (int j=0; j<i; j++)
out.println(inputLines[j]);
printTrailer(out);
server.close();
}
private void printHeader(PrintWriter out) {
out.println("HTTP/1.0 200 Document followsrn" +
"Server: " + serverName + "rn" +
"Content-Type: text/htmlrn" +
"rn" +
"<!DOCTYPE HTML PUBLIC " +
""-//W3C//DTD HTML 4.0//EN">n" +
"<HTML>n" +
...
"</HEAD>n");
}
...
}
Network Programming: Servers15 www.corewebprogramming.com
EchoServer in Action
EchoServer shows data sent by the browser
Network Programming: Servers16 www.corewebprogramming.com
Adding Multithreading
import java.net.*;
import java.io.*;
/** A multithreaded variation of EchoServer. */
public class ThreadedEchoServer extends EchoServer
implements Runnable {
public static void main(String[] args) {
int port = 8088;
if (args.length > 0)
port = Integer.parseInt(args[0]);
ThreadedEchoServer echoServer =
new ThreadedEchoServer(port, 0);
echoServer.serverName = "Threaded Echo Server 1.0";
echoServer.listen();
}
public ThreadedEchoServer(int port, int connections) {
super(port, connections);
}
Network Programming: Servers17 www.corewebprogramming.com
Adding Multithreading
(Continued)
public void handleConnection(Socket server) {
Connection connectionThread =
new Connection(this, server);
connectionThread.start();
}
public void run() {
Connection currentThread =
(Connection)Thread.currentThread();
try {
super.handleConnection(currentThread.serverSocket);
} catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}
}
Network Programming: Servers18 www.corewebprogramming.com
Adding Multithreading
(Continued)
/** This is just a Thread with a field to store a
* Socket object. Used as a thread-safe means to pass
* the Socket from handleConnection to run.
*/
class Connection extends Thread {
protected Socket serverSocket;
public Connection(Runnable serverObject,
Socket serverSocket) {
super(serverObject);
this.serverSocket = serverSocket;
}
}
Network Programming: Servers19 www.corewebprogramming.com
Summary
• Create a ServerSocket; specify port number
• Call accept to wait for a client connection
– Once a connection is established, a Socket object is
created to communicate with client
• Browser requests consist of a GET, POST, or
HEAD line followed by a set of request headers
and a blank line
• For the HTTP server response, send the status
line (HTTP/1.0 200 OK), Content-Type, blank
line, and document
• For improved performance, process each
request in a separate thread
20 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Questions?

More Related Content

What's hot

Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websocketsWim Godden
 
Juglouvain http revisited
Juglouvain http revisitedJuglouvain http revisited
Juglouvain http revisitedmarctritschler
 
Your app lives on the network - networking for web developers
Your app lives on the network - networking for web developersYour app lives on the network - networking for web developers
Your app lives on the network - networking for web developersWim Godden
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
HTTP - The Protocol of Our Lives
HTTP - The Protocol of Our LivesHTTP - The Protocol of Our Lives
HTTP - The Protocol of Our LivesBrent Shaffer
 
Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)maamir farooq
 
Apache Server Tutorial
Apache Server TutorialApache Server Tutorial
Apache Server TutorialJagat Kothari
 
Introduction to HTTP
Introduction to HTTPIntroduction to HTTP
Introduction to HTTPYihua Huang
 
Web Server Administration
Web Server AdministrationWeb Server Administration
Web Server Administrationwebhostingguy
 

What's hot (17)

Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Web
WebWeb
Web
 
Phd3
Phd3Phd3
Phd3
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 
Juglouvain http revisited
Juglouvain http revisitedJuglouvain http revisited
Juglouvain http revisited
 
Your app lives on the network - networking for web developers
Your app lives on the network - networking for web developersYour app lives on the network - networking for web developers
Your app lives on the network - networking for web developers
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
HTTP - The Protocol of Our Lives
HTTP - The Protocol of Our LivesHTTP - The Protocol of Our Lives
HTTP - The Protocol of Our Lives
 
Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)Lec 7(HTTP Protocol)
Lec 7(HTTP Protocol)
 
Http protocol
Http protocolHttp protocol
Http protocol
 
Apache Web Server Setup 3
Apache Web Server Setup 3Apache Web Server Setup 3
Apache Web Server Setup 3
 
Apache Server Tutorial
Apache Server TutorialApache Server Tutorial
Apache Server Tutorial
 
Introduction to HTTP
Introduction to HTTPIntroduction to HTTP
Introduction to HTTP
 
T2
T2T2
T2
 
Apache web service
Apache web serviceApache web service
Apache web service
 
Web Server Administration
Web Server AdministrationWeb Server Administration
Web Server Administration
 

Viewers also liked

11 protips for smooth web application deployment
11 protips for smooth web application deployment11 protips for smooth web application deployment
11 protips for smooth web application deploymentMichelangelo van Dam
 
Organizata per Ruajtjen e Zhvillimin e Gjirokastres
Organizata per Ruajtjen e Zhvillimin e GjirokastresOrganizata per Ruajtjen e Zhvillimin e Gjirokastres
Organizata per Ruajtjen e Zhvillimin e GjirokastresAlbanian Tourism Low-Cost
 
Tri-State Moving Services, General Presentation
Tri-State Moving Services, General PresentationTri-State Moving Services, General Presentation
Tri-State Moving Services, General Presentationjscherrer
 
Development And Management Strategy Manik
Development And Management Strategy ManikDevelopment And Management Strategy Manik
Development And Management Strategy ManikSultan Giasuddin
 
Ucrânia em ebulição e suas consequências
Ucrânia em ebulição e suas consequênciasUcrânia em ebulição e suas consequências
Ucrânia em ebulição e suas consequênciasRoberto Rabat Chame
 
Cocinas antiguas
Cocinas antiguasCocinas antiguas
Cocinas antiguaspilarandres
 
MacroCar Talaver S.L.
MacroCar Talaver S.L. MacroCar Talaver S.L.
MacroCar Talaver S.L. GaLorena
 
Social media questions marketers need to answer understanding platform
Social media questions marketers need to answer understanding platformSocial media questions marketers need to answer understanding platform
Social media questions marketers need to answer understanding platformadverteaze.com
 
12advanced Swing
12advanced Swing12advanced Swing
12advanced SwingAdil Jafri
 
Happy Easter! Hristos A Inviat!
Happy Easter! Hristos A Inviat!Happy Easter! Hristos A Inviat!
Happy Easter! Hristos A Inviat!Mihaela
 
UX Week 2011 Sketchnotes
UX Week 2011 SketchnotesUX Week 2011 Sketchnotes
UX Week 2011 SketchnotesMark Congiusta
 
Waiting for Medicare’s Second Stage
Waiting for Medicare’s Second StageWaiting for Medicare’s Second Stage
Waiting for Medicare’s Second StageOmar Ha-Redeye
 
1M/1M vs. YCombinator
1M/1M vs. YCombinator1M/1M vs. YCombinator
1M/1M vs. YCombinatorSramana Mitra
 
Wie man mehr Follower auf Twitter gewinnt
Wie man mehr Follower auf Twitter gewinntWie man mehr Follower auf Twitter gewinnt
Wie man mehr Follower auf Twitter gewinntTrajan Tosev
 
User Experience Just Doesn’t Matter
User Experience Just Doesn’t MatterUser Experience Just Doesn’t Matter
User Experience Just Doesn’t MatterMark Congiusta
 

Viewers also liked (20)

11 protips for smooth web application deployment
11 protips for smooth web application deployment11 protips for smooth web application deployment
11 protips for smooth web application deployment
 
Organizata per Ruajtjen e Zhvillimin e Gjirokastres
Organizata per Ruajtjen e Zhvillimin e GjirokastresOrganizata per Ruajtjen e Zhvillimin e Gjirokastres
Organizata per Ruajtjen e Zhvillimin e Gjirokastres
 
Tri-State Moving Services, General Presentation
Tri-State Moving Services, General PresentationTri-State Moving Services, General Presentation
Tri-State Moving Services, General Presentation
 
La toma
La tomaLa toma
La toma
 
Development And Management Strategy Manik
Development And Management Strategy ManikDevelopment And Management Strategy Manik
Development And Management Strategy Manik
 
Ucrânia em ebulição e suas consequências
Ucrânia em ebulição e suas consequênciasUcrânia em ebulição e suas consequências
Ucrânia em ebulição e suas consequências
 
Cocinas antiguas
Cocinas antiguasCocinas antiguas
Cocinas antiguas
 
MacroCar Talaver S.L.
MacroCar Talaver S.L. MacroCar Talaver S.L.
MacroCar Talaver S.L.
 
Social media questions marketers need to answer understanding platform
Social media questions marketers need to answer understanding platformSocial media questions marketers need to answer understanding platform
Social media questions marketers need to answer understanding platform
 
12advanced Swing
12advanced Swing12advanced Swing
12advanced Swing
 
Happy Easter! Hristos A Inviat!
Happy Easter! Hristos A Inviat!Happy Easter! Hristos A Inviat!
Happy Easter! Hristos A Inviat!
 
Barátság zene
Barátság zeneBarátság zene
Barátság zene
 
UX Week 2011 Sketchnotes
UX Week 2011 SketchnotesUX Week 2011 Sketchnotes
UX Week 2011 Sketchnotes
 
Waiting for Medicare’s Second Stage
Waiting for Medicare’s Second StageWaiting for Medicare’s Second Stage
Waiting for Medicare’s Second Stage
 
Who Is Val
Who Is ValWho Is Val
Who Is Val
 
1M/1M vs. YCombinator
1M/1M vs. YCombinator1M/1M vs. YCombinator
1M/1M vs. YCombinator
 
Cyberbeegroup2
Cyberbeegroup2Cyberbeegroup2
Cyberbeegroup2
 
Water plants rosi
Water plants rosiWater plants rosi
Water plants rosi
 
Wie man mehr Follower auf Twitter gewinnt
Wie man mehr Follower auf Twitter gewinntWie man mehr Follower auf Twitter gewinnt
Wie man mehr Follower auf Twitter gewinnt
 
User Experience Just Doesn’t Matter
User Experience Just Doesn’t MatterUser Experience Just Doesn’t Matter
User Experience Just Doesn’t Matter
 

Similar to 16network Programming Servers

Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#caohansnnuedu
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxkacie8xcheco
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenVannaSchrader3
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxalfredacavx97
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded wsmile790243
 
11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA) 11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA) Nguyen Tuan
 
Iss letcure 7_8
Iss letcure 7_8Iss letcure 7_8
Iss letcure 7_8Ali Habeeb
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23Techvilla
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docxhanneloremccaffery
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopyayaria
 
WebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemonWebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemonGeert Van Pamel
 

Similar to 16network Programming Servers (20)

Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
28 networking
28  networking28  networking
28 networking
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
Sockets
SocketsSockets
Sockets
 
Web Server and how we can design app in C#
Web Server and how we can design app  in C#Web Server and how we can design app  in C#
Web Server and how we can design app in C#
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Os 2
Os 2Os 2
Os 2
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w
 
11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA) 11.Open Data Protocol(ODATA)
11.Open Data Protocol(ODATA)
 
Iss letcure 7_8
Iss letcure 7_8Iss letcure 7_8
Iss letcure 7_8
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
WebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemonWebTalk - Implementing Web Services with a dedicated Java daemon
WebTalk - Implementing Web Services with a dedicated Java daemon
 

More from Adil Jafri

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net BibleAdil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx TutorialsAdil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbAdil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash TutorialAdil Jafri
 

More from Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Php How To
Php How ToPhp How To
Php How To
 
Php How To
Php How ToPhp How To
Php How To
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
Javascript
JavascriptJavascript
Javascript
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
 
Html Css
Html CssHtml Css
Html Css
 
Digwc
DigwcDigwc
Digwc
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 
C Programming
C ProgrammingC Programming
C Programming
 

Recently uploaded

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

16network Programming Servers

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Network Programming: Servers
  • 2. Network Programming: Servers2 www.corewebprogramming.com Agenda • Steps for creating a server 1. Create a ServerSocket object 2. Create a Socket object from ServerSocket 3. Create an input stream 4. Create an output stream 5. Do I/O with input and output streams 6. Close the socket • A generic network server • Accepting connections from browsers • Creating an HTTP server • Adding multithreading to an HTTP server
  • 3. Network Programming: Servers3 www.corewebprogramming.com Steps for Implementing a Server 1. Create a ServerSocket object ServerSocket listenSocket = new ServerSocket(portNumber); 2. Create a Socket object from ServerSocket while(someCondition) { Socket server = listenSocket.accept(); doSomethingWith(server); } • Note that it is quite common to have doSomethingWith spin off a separate thread 3. Create an input stream to read client input BufferedReader in = new BufferedReader (new InputStreamReader(server.getInputStream()));
  • 4. Network Programming: Servers4 www.corewebprogramming.com Steps for Implementing a Server 4. Create an output stream that can be used to send info back to the client. // Last arg of true means autoflush stream // when println is called PrintWriter out = new PrintWriter(server.getOutputStream(), true) 5. Do I/O with input and output Streams – Most common input: readLine – Most common output: println 6. Close the socket when done server.close(); – This closes the associated input and output streams.
  • 5. Network Programming: Servers5 www.corewebprogramming.com A Generic Network Server import java.net.*; import java.io.*; /** A starting point for network servers. */ public class NetworkServer { protected int port, maxConnections; /** Build a server on specified port. It will continue * to accept connections (passing each to * handleConnection) until an explicit exit * command is sent (e.g. System.exit) or the * maximum number of connections is reached. Specify * 0 for maxConnections if you want the server * to run indefinitely. */ public NetworkServer(int port, int maxConnections) { this.port = port; this.maxConnections = maxConnections; } ...
  • 6. Network Programming: Servers6 www.corewebprogramming.com A Generic Network Server (Continued) /** Monitor a port for connections. Each time one * is established, pass resulting Socket to * handleConnection. */ public void listen() { int i=0; try { ServerSocket listener = new ServerSocket(port); Socket server; while((i++ < maxConnections) || (maxConnections == 0)) { server = listener.accept(); handleConnection(server); } } catch (IOException ioe) { System.out.println("IOException: " + ioe); ioe.printStackTrace(); } }
  • 7. Network Programming: Servers7 www.corewebprogramming.com A Generic Network Server (Continued) ... protected void handleConnection(Socket server) throws IOException{ BufferedReader in = SocketUtil.getBufferedReader(server); PrintWriter out = SocketUtil.getPrintWriter(server); System.out.println ("Generic Network Server:n" + "got connection from " + server.getInetAddress().getHostName() + "n" + "with first line '" + in.readLine() + "'"); out.println("Generic Network Server"); server.close(); } } – Override handleConnection to give your server the behavior you want.
  • 8. Network Programming: Servers8 www.corewebprogramming.com Using Network Server public class NetworkServerTest { public static void main(String[] args) { int port = 8088; if (args.length > 0) { port = Integer.parseInt(args[0]); } NetworkServer server = new NetworkServer(port, 1); server.listen(); } }
  • 9. Network Programming: Servers9 www.corewebprogramming.com Network Server: Results • Accepting a Connection from a WWW Browser – Suppose the above test program is started up on port 8088 of server.com: server> java NetworkServerTest – Then, a standard Web browser on client.com requests http://server.com:8088/foo/, yielding the following back on server.com: Generic Network Server: got connection from client.com with first line 'GET /foo/ HTTP/1.0'
  • 10. Network Programming: Servers10 www.corewebprogramming.com HTTP Requests and Responses • Request GET /~gates/ HTTP/1.0 Header1: … Header2: … … HeaderN: … Blank Line – All request headers are optional except for Host (required only for HTTP/1.1 requests) – If you send HEAD instead of GET, the server returns the same HTTP headers, but no document • Response HTTP/1.0 200 OK Content-Type: text/html Header2: … … HeaderN: … Blank Line <!DOCTYPE …> <HTML> … </HTML> – All response headers are optional except for Content-Type
  • 11. Network Programming: Servers11 www.corewebprogramming.com A Simple HTTP Server • Idea 1. Read all the lines sent by the browser, storing them in an array • Use readLine a line at a time until an empty line – Exception: with POST requests you have to read some extra data 2. Send an HTTP response line (e.g. "HTTP/1.0 200 OK") 3. Send a Content-Type line then a blank line • This indicates the file type being returned (HTML in this case) 4. Send an HTML file showing the lines that were sent 5. Close the connection
  • 12. Network Programming: Servers12 www.corewebprogramming.com EchoServer import java.net.*; import java.io.*; import java.util.StringTokenizer; /** A simple HTTP server that generates a Web page * showing all of the data that it received from * the Web client (usually a browser). */ public class EchoServer extends NetworkServer { protected int maxInputLines = 25; protected String serverName = "EchoServer 1.0"; public static void main(String[] args) { int port = 8088; if (args.length > 0) port = Integer.parseInt(args[0]); EchoServer echoServer = new EchoServer(port, 0); echoServer.listen(); } public EchoServer(int port, int maxConnections) { super(port, maxConnections); }
  • 13. Network Programming: Servers13 www.corewebprogramming.com EchoServer (Continued) public void handleConnection(Socket server) throws IOException{ System.out.println(serverName + ": got connection from " + server.getInetAddress().getHostName()); BufferedReader in = SocketUtil.getBufferedReader(server); PrintWriter out = SocketUtil.getPrintWriter(server); String[] inputLines = new String[maxInputLines]; int i; for (i=0; i<maxInputLines; i++) { inputLines[i] = in.readLine(); if (inputLines[i] == null) // Client closes connection break; if (inputLines[i].length() == 0) { // Blank line if (usingPost(inputLines)) { readPostData(inputLines, i, in); i = i + 2; } break; } } ...
  • 14. Network Programming: Servers14 www.corewebprogramming.com EchoServer (Continued) printHeader(out); for (int j=0; j<i; j++) out.println(inputLines[j]); printTrailer(out); server.close(); } private void printHeader(PrintWriter out) { out.println("HTTP/1.0 200 Document followsrn" + "Server: " + serverName + "rn" + "Content-Type: text/htmlrn" + "rn" + "<!DOCTYPE HTML PUBLIC " + ""-//W3C//DTD HTML 4.0//EN">n" + "<HTML>n" + ... "</HEAD>n"); } ... }
  • 15. Network Programming: Servers15 www.corewebprogramming.com EchoServer in Action EchoServer shows data sent by the browser
  • 16. Network Programming: Servers16 www.corewebprogramming.com Adding Multithreading import java.net.*; import java.io.*; /** A multithreaded variation of EchoServer. */ public class ThreadedEchoServer extends EchoServer implements Runnable { public static void main(String[] args) { int port = 8088; if (args.length > 0) port = Integer.parseInt(args[0]); ThreadedEchoServer echoServer = new ThreadedEchoServer(port, 0); echoServer.serverName = "Threaded Echo Server 1.0"; echoServer.listen(); } public ThreadedEchoServer(int port, int connections) { super(port, connections); }
  • 17. Network Programming: Servers17 www.corewebprogramming.com Adding Multithreading (Continued) public void handleConnection(Socket server) { Connection connectionThread = new Connection(this, server); connectionThread.start(); } public void run() { Connection currentThread = (Connection)Thread.currentThread(); try { super.handleConnection(currentThread.serverSocket); } catch(IOException ioe) { System.out.println("IOException: " + ioe); ioe.printStackTrace(); } } }
  • 18. Network Programming: Servers18 www.corewebprogramming.com Adding Multithreading (Continued) /** This is just a Thread with a field to store a * Socket object. Used as a thread-safe means to pass * the Socket from handleConnection to run. */ class Connection extends Thread { protected Socket serverSocket; public Connection(Runnable serverObject, Socket serverSocket) { super(serverObject); this.serverSocket = serverSocket; } }
  • 19. Network Programming: Servers19 www.corewebprogramming.com Summary • Create a ServerSocket; specify port number • Call accept to wait for a client connection – Once a connection is established, a Socket object is created to communicate with client • Browser requests consist of a GET, POST, or HEAD line followed by a set of request headers and a blank line • For the HTTP server response, send the status line (HTTP/1.0 200 OK), Content-Type, blank line, and document • For improved performance, process each request in a separate thread
  • 20. 20 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Questions?