COMP201 Java Programming Part III: Advanced Features Topic 14: Networking Volume II,Chapter 3.

Slides:



Advertisements
Similar presentations
COEN 445 Communication Networks and Protocols Lab 4
Advertisements

Lecture 10: Networking using Socket Programming. Client-Server Model b The term server applies to any program that offers a service that can be reached.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
COMP201 Java Programming Part III: Advanced Features Topic 13: Networking Volume II,Chapter 3.
Socket Programming.
1 Java Networking – Part I CS , Spring 2008/9.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
COMP1681 / SE15 Introduction to Programming
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Client/Server In Java An Introduction to TCP/IP and Sockets.
28-Jun-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University.
15-Jul-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
EE2E1. JAVA Programming Lecture 9 Network Programming.
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
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.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Appendix F: Network Programming in Java ©SoftMoore ConsultingSlide 1.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Application Protocols: HTTP CSNB534 Semester 2, 2007/2008 Asma Shakil.
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.
COMP201 Java Programming Part III: Advanced Features Topic 13: Networking Volume II,Chapter 3.
4-Oct-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you send.
DBI Representation and Management of Data on the Internet.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 7: HTTP and CGI Fundamentals of Web Programming.
Internet Applications and Network Programming Dr. Abraham Professor UTPA.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
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.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
Web Design & Development 1 Lec - 21 Umair Javed. Web Design & Development 2 Socket Programming.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/11) Java Sockets and Simple Networking Joel Adams and Jeremy Frens.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
Internet Applications (Cont’d) Basic Internet Applications – World Wide Web (WWW) Browser Architecture Static Documents Dynamic Documents Active Documents.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Networking A network represents interconnection of computers that is capable.
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.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Java Networking I IS Outline  Quiz #3  Network architecture  Protocols  Sockets  Server Sockets  Multi-threaded Servers.
Network Programming James Atlas July 10, James Atlas - CISC3702 Review Multi-Threaded Programming Multi-Threaded Programming  Processes  Threads.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
1 Network Communications A Brief Introduction. 2 Network Communications.
Network Programming. These days almost all devices.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit9: Internet programming 1.
Object-Orientated Analysis, Design and Programming
MCA – 405 Elective –I (A) Java Programming & Technology
Networking with Java 2.
Network Programming Introduction
Lecture 9 Network Programming
Clients and Servers 19-Nov-18.
Basic Protocols 24-Nov-18.
URL in Java C343 Lab (Week 13).
Clients and Servers 1-Dec-18.
Basic Protocols 19-Feb-19.
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Presentation transcript:

COMP201 Java Programming Part III: Advanced Features Topic 14: Networking Volume II,Chapter 3

COMP201 Topic 14 / Slide 2 Outline l Networking basics n IP addresses, ports, protocols, client-server interaction l Socket-level programming n Writing a client n Writing a server l URL connections and web servers n Retrieving information n Sending information

COMP201 Topic 14 / Slide 3 Networking Basics l Internet protocol (IP) address n Every host on Internet has a unique IP address , , , n More convenient to refer to using hostname string cs.ust.hk, tom.com, localhost n Domain Naming Service (DNS) maps names to numbers n One hostname can correspond to multiple internet addresses: tom.com: , , (down to one now)

COMP201 Topic 14 / Slide 4 java.net.InetAddress class converts between hostnames and internet addresses InetAddress tm = InetAddress.getByName(“tom.com"); InetAddress tm= InetAddress.getByName(“localhost"); // InetAddress tm = InetAddress.getLocalHost(); l Can get array of addresses (if more than one) InetAddress[] addrs; addrs=InetAddress.getAllByName(“tom.com"); for (int i = 0; i < addr.length; i++) System.out.println(addrs[i].getHostAddress()); InetAddressTest.java Networking Basics

COMP201 Topic 14 / Slide 5 l Ports l A port identifies a service within a host Many different services can be running on the host l Many standard port numbers are pre-assigned time of day 13, ftp 21, telnet 23, smtp 25, finger 79, http 80 see /etc/services on workstation for list of all assigned ports l IP address + port number = "phone number“ for service Networking Basics

COMP201 Topic 14 / Slide 6 l protocols : rules that facilitate communications between machines Time of day just reports time, ftp has put/get commands, etc. l Protocols must be standardized and documented So machines can reliably work with one another l TCP (Transmission Control Protocol) vs UDP (User Datagram Protocol, good for, e.g., video delivery) Networking Basics

COMP201 Topic 14 / Slide 7 l Client-Server interaction l Communication between hosts is two-way, but usually the two hosts take different roles l Server waits for client to make request Server registered on a known port with the host ("public phone number") Usually running in endless loop Listens for incoming client connections Networking Basics

COMP201 Topic 14 / Slide 8 l Client "calls" server to start a conversation Client making calls uses hostname/IP address and port number Sends request and waits for response l Standard services always running ftp, http, smtp, etc. server running on host using expected port l Server offers shared resource (information,database, files, printer, compute power) to clients Networking Basics

COMP201 Topic 14 / Slide 9 Using telnet to try out some services of servers: l Telnet assumes you want to connect to port 23 on the receiving host (port 23 is where the telnet server is listening) l However there is an optional argument after the hostname that allows you to connect to a different port l Try the following Get time: telnet time-A.timefreq.bldrdoc.gov 13 Finger some one: telnet cssu100.cs.ust.hk 79 & type a username Get HTML page: telnet tom.com 80 and enter a GET command Networking Basics

COMP201 Topic 14 / Slide 10 Socket-Level Programming l A socket is a bi-directional communication channel between hosts l Send and receive data using streams ClientServer OutputStream InputStream OutputStream l Next: n How to write a client n How to write a server

COMP201 Topic 14 / Slide 11 l To write a client Create a new Socket with hostname and port number of the connection Socket s = New Socket(String hostName,int portNumber); Call s.getOutputStream() and s.getInputStream() to get streams for sending and receiving infomation n Need to learn protocol used to communicate –Know how to properly form requests to send to server –Know how to interpret the server’s responses Socket-Level Programming/Client

COMP201 Topic 14 / Slide 12 Socket-Level Programming/Client l Example: A client using http to request page Socket s = new Socket(“tom.com", 80); PrintWriter send = new PrintWriter(s.getOutputStream()); send.print("GET \n"); send.flush(); BufferedReader recv = new BufferedReader( new InputStreamReader(s.getInputStream())); String line; while ((line = recv.readLine()) != null) System.out.println(line); s.close() //HttpTest.java. This is basically what web browsers do.

COMP201 Topic 14 / Slide 13 Socket-Level Programming/Client Use setSoTimeout method to limit the amount of time waiting for data Socket s = new Socket(“tom.com", 80); s.setSoTimeout( ); // time out after 10 seconds l Can still wait indefinitely for initial connection (construction of socket object).

COMP201 Topic 14 / Slide 14 Socket-Level Programming/Client Solution: Construct socket in a separate thread and use the join method to time out. class SocketOpener implements Runnable { public SocketOpener(String aHost, int aPort) { socket = null; host = aHost; port = aPort; } public void run() { try { socket = new Socket(host, port);} catch (IOException exception) {} } public Socket getSocket() { return socket; } … private String host; private int port; private Socket socket;

COMP201 Topic 14 / Slide 15 Socket-Level Programming/Client class SocketOpener implements Runnable { // method to be called by main thread public static Socket openSocket(String aHost, int aPort, int timeout) { SocketOpener opener = new SocketOpener(aHost, aPort); Thread t = new Thread(opener); t.start(); try { t.join(timeout); // wait at most timeout milliseconds } // for the thread to dead catch (InterruptedException exception){} return opener.getSocket(); } SocketOpenerTest.java

COMP201 Topic 14 / Slide 16 Socket-Level Programming/Server l To write a server Create a new ServerSocket with a port number to listen on the port ServerSocket s = New ServerSocket( portNumber); Use accept() to listen on the port. accept () returns a socket incoming when a client calls Socket incoming = s.accept(); Call incoming.getOutputStream() and incoming.getInputStream() to get streams for sending and receiving information

COMP201 Topic 14 / Slide 17 Socket-Level Programming/Server l Example: Echo server ServerSocket s = new ServerSocket(8189); while (true) { Socket incoming = s.accept( ); BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */ ); out.println( "Hello! Enter BYE to exit." ); … } EchoServer.java

COMP201 Topic 14 / Slide 18 Socket-Level Programming/Server l Multithread server: starts a separate thread for each connection. public class ThreadedEchoServer { public static void main(String[] args ) { int i = 1; try{ServerSocket s = new ServerSocket(8190); while (true) { Socket incoming = s.accept( ); System.out.println("Spawning " + i); new ThreadedEchoHandler(incoming, i).start(); i++; } } catch (Exception e) …. // ThreadedEchoServer.java

COMP201 Topic 14 / Slide 19 Socket-Level Programming/Server class ThreadedEchoHandler extends Thread { public ThreadedEchoHandler(Socket i, int c) { incoming = i; counter = c; } public void run() { try { BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); … private Socket incoming; private int counter; }

COMP201 Topic 14 / Slide 20 l ICQServer.java n A simple server that listens on port n Connect two clients so that they can talk to each other. n Can handle more than one pairs. n See code for details. Socket-Level Programming/Server

COMP201 Topic 14 / Slide 21 URL Connections l URL stands for Uniform Resource Locator Neat scheme for uniquely identifying all kinds of network resources l Basic form : ftp://ftp.cs.ust.hk/pub/lzhang/teach/201/codes/HttpTest/HttpTest.java file:/MyDisk/Letters/ToMom Protocols include files, http, ftp, gopher, news, mailto, etc. l Connecting to a URL, the hard way Manually parse out the host, protocol, path from URL Create a socket to host Use protocol to send the right request & interpret response But Java makes this much easier than that...

COMP201 Topic 14 / Slide 22 URL Connections/Retrieve Info Open connection with java.net.URL URL url1 = new URL(“ URL url2 = new URL (“ftp://ftp.cs.ust.hk/pub/lzhang/teach/201/codes/net/HttpT est/HttpTest.java”); To fetch contents of resource, use openStream method of URL, which returns a InputStream InputStream in1 = url1.openStream(); InputStream in2 = url2.openStream(); Now we can nest the InputStreams with other Java streams to retrieve contents l Advantages 1. No need to worry about protocol details & port. 2. Connection to particular file, not easy to do at Socket level

COMP201 Topic 14 / Slide 23 URL Connections/Retrieve Info Use java.net.URLConnection for additional info about resource 1. Create URLConnection object from URL, URLConnection cnn = url.openConnection(); 2. Set properties of connections: E.g. setDoOutPut(true) for sending information to the server 3. Make connection: cnn.connect(); 4. Query header information: getContentType, getContentLength, getContentEncoding, getDate, getExpiration, getLastModified 5. getInputStream for reading and getOutputStream for writing URLConnectionTest.java

COMP201 Topic 14 / Slide 24 URL Connections/Sending Info l Web servers receive information from clients using either GET or POST l … l l Appropriate CGI (common gateway interface) script is called to process info received and produce an HTML page to send back to client l CGI scripts usually written in C, Perl, shell script. (Out of the scope of this course.) l Will discuss servlets, Java alternative to CGI scripts

COMP201 Topic 14 / Slide 25 URL Connections/Sending Info l Send information to server using GET l Attach parameters to the end of URL l Separate parameters using “&” and encode parameters as follows to avoid misinterpretation (URL encoding) l Static String encode (String s) l Replace space with “+” l Replace each non-alphanumeric character with “%” followed by the hexadecimal code of the character “Mastering C++”  “Mastering+C%2b%2b” Disadvantage: long parameter string, might exceed limits of browsers. GetTest.java

COMP201 Topic 14 / Slide 26 URL Connections/Sending Info l Sending information to server using POST: Open URLConnection and send parameter using a stream 1. Open a URLConnection: URL url = new URL(“ URLConnection cnn = url.openConnection(); 2. Set up connection for output: cnn.setDoOutput(true); 3. Get a stream for sending data: PrinterWriter out = new PrintWriter(cnn.getOutputStream()); 4. Send parameters Out.print(name1 + “=“ + URLEncoder.encode(value1) + “&” ); Out.print(name2 + “=“ + URLEncoder.encode(value2) + “\n”); PostTest.java