Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.

Slides:



Advertisements
Similar presentations
CS Network Programming CS 3331 Fall CS 3331 Outline Socket programming Remote method invocation (RMI)
Advertisements

Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Using TCP sockets in Java Created by M Bateman, A Ruddle & C Allison As part of the TCP View project.
Referring to Java API Specifications
Socket Programming By Ratnakar Kamath. What Is a Socket? Server has a socket bound to a specific port number. Client makes a connection request. Server.
COEN 445 Communication Networks and Protocols Lab 4
Java Threads A tool for concurrency. OS schedules processes Ready Running 200 Blocked A process loses the CPU and another.
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
Java Networking -- Socket Server socket class: ServerSocket wait for requests from clients. after a request is received, a client socket is generated.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Java sockets. From waiting.
Serving HTTP NetworkServer.java EchoServer.java PostForm.html PostForm.html Browser EchoServer Response Using POST GetForm.html GetForm.html Browser EchoServer.
1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University.
1 First app – simplechat1 Reminder: what’s the point?  To build on ocsf framework.  Simple requirements: echo all messages to all clients.  Use only.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
Web Proxy Server. Proxy Server Introduction Returns status and error messages. Handles http CGI requests. –For more information about CGI please refer.
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
Web Security Programming I Building Security in from the Start Except where otherwise noted all portions of this work are Copyright (c) 2007 Google and.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Network Programming: Clients. Agenda l Creating sockets l Implementing a generic network client l Parsing data using StringTokenizer l Retrieving files.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
DBI Representation and Management of Data on the Internet.
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Lab 2C Primer I/O in Java Sockets Threads More Java Stuffs.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 22.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Networking and Concurrency COMP.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Lab 2 Primer Assignment 3 Structure File I/O More parsing and HTTP Formatting.
VII. Sockets. 1. What is a Socket? A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes.
Java Server Programming Web Interface for Java Programs.
© Marty Hall, Larry Brown Web core programming 1 Using Applets as Front Ends to Server-Side Programs.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Programming II Java Network (I) Java Programming II.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Data Communication EDA344, DIT420 Description of Lab 1 and Optional Programming HTTP Assignment Bapi Chatterjee Prajith R G.
Using Applets as Front Ends to Server-Side Programs.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
SOCKET PROGRAMMING WITH JAVA By Collin Donaldson.
Liang, Oreilly, Herbert Schildt, Joseph O’Neil, Simon Roberts, IBM Corp Advanced Java Programming CSE 7345/5345/ NTU 531 Multithreaded/Sockets/Server Welcome.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Java 13. Networking public class SumTest {
Echo Networking COMP
Threads in Java Two ways to start a thread
Lecture 21 Sockets 1 (Not in D&D) Date.
CSE 341, S. Tanimoto Java networking-
Client-server Programming
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
Multiplexing/Demux.
Clients and Servers 19-Jul-19.
CS18000: Problem Solving and Object-Oriented Programming
Clients and Servers 13-Sep-19.
Presentation transcript:

Network Programming: Servers

Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input stream Create an output stream Do I/O with input and output streams Close the socket l A generic network server l Accepting connections from browsers l Creating an HTTP server l Adding multithreading to an HTTP server

Steps for Implementing a Server l Create a ServerSocket object ServerSocket listenSocket = new ServerSocket(portNumber); l 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 l Create an input stream to read client input BufferedReader in = new BufferedReader (new InputStreamReader(server.getInputStream()));

Steps for Implementing a Server l 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) l Do I/O with input and output Streams Most common input: readLine Most common output: println l Close the socket when done server.close(); This closes the associated input and output streams.

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; }...

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(); }

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.

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 Server: Results l 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 yielding the following back on server.com : Generic Network Server: got connection from client.com with first line 'GET /foo/ HTTP/1.0'

HTTP Requests and Responses l 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 l Response HTTP/ OK Content-Type: text/html Header2: … … HeaderN: … Blank Line … All response headers are optional except for Content-Type

A Simple HTTP Server l Idea 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 Send an HTTP response line (e.g. "HTTP/ OK") Send a Content-Type line then a blank line This indicates the file type being returned (HTML in this case) Send an HTML file showing the lines that were sent Close the connection

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); }

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; }...

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/ Document follows\r\n" + "Server: " + serverName + "\r\n" + "Content-Type: text/html\r\n" + "\r\n" + "<!DOCTYPE HTML PUBLIC " + "\"-//W3C//DTD HTML 4.0//EN\">\n" + " \n" +... " \n"); }... }

EchoServer in Action EchoServer shows data sent by the browser

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); }

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(); }

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; }

Summary l 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 l Browser requests consist of a GET, POST, or HEAD line followed by a set of request headers and a blank line l For the HTTP server response, send the status line (HTTP/ OK), Content-Type, blank line, and document l For improved performance, process each request in a separate thread

Questions?