Networking with Java. Introduction to Networking.

Slides:



Advertisements
Similar presentations
Networking with Java 1. Introduction to Networking 2.
Advertisements

Network Programming Chapter 11 Lecture 6. Networks.
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
Socket Programming.
1 Creating a network app Write programs that  run on different end systems and  communicate over a network.  e.g., Web: Web server software communicates.
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
1 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
1 Java Networking CS , Spring 2008/9. 2 Today’s Menu Networking Basics  TCP, UDP, Ports, DNS, Client-Server Model TCP/IP in Java Sockets URL 
1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast.
Networking with Java 1: The Client Side. Introduction to Networking.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
1 Java Networking – part I CS , Winter 2007/8.
13-Jul-15 Sockets and URLs. 2 Sockets A socket is a low-level software device for connecting two computers together Sockets can also be used to connect.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
1 Networking with Java. 2 Introduction to Networking.
1 Java Networking CS , Spring Today’s Menu Networking Basics  TCP, UDP, Ports, DNS, Client-Server Model TCP/IP in Java Sockets URL  The.
JAVA Socket Programming Source: by Joonbok Lee, KAIST, 2003.
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
CS 352-Socket Programming & Threads Dept. of Computer Science Rutgers University (Thanks,this slides taken from er06/
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.
2: Application Layer1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
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.
DBI Representation and Management of Data on the Internet.
-1- Georgia State UniversitySensorweb Research Laboratory CSC4220/6220 Computer Networks Dr. WenZhan Song Associate Professor, Computer Science.
Socket Programming Lee, Sooyong
Network Programming and Sockets CPSC 363 Computer Networks Ellen Walker Hiram College (Includes figures from Computer Networking by Kurose & Ross, © Addison.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
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.
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.
Java Socket programming. Socket programming with TCP.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
NETWORK PROGRAMMING.
Socket Programming Using JAVA Asma Shakil Semester 1, 2008/2009.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
1 COMP 431 Internet Services & Protocols Client/Server Computing & Socket Programming Jasleen Kaur February 2, 2016.
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.
URL Programming Mimi Opkins CECS277. What is a URL?  URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
1 CSCD 330 Network Programming Winter 2016 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 6 Application.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
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.
1 Network Communications A Brief Introduction. 2 Network Communications.
Network Programming. These days almost all devices.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 33 Networking.
Object-Orientated Analysis, Design and Programming
MCA – 405 Elective –I (A) Java Programming & Technology
Networking with Java 2.
Network Programming Introduction
Chapter 2: outline 2.1 principles of network applications
Socket programming - Java
Socket Programming 2: Application Layer.
Chapter 2: Application layer
Process-to-Process Delivery: UDP, TCP
Exceptions and networking
Presentation transcript:

Networking with Java

Introduction to Networking

Protocols Hi TCP connection request Hi TCP connection reply Got the time? GET 2:00 time

Internet Architecture Model Application (HTTP, FTP) DATA Transport (TCP,UDP) HEADERDATA Network (IP) HEADER DATA Link (LINK) HEADER DATA

TCP ( Transmission-Control Protocol) Enables symmetric byte-stream transmission between two endpoints (applications) Reliable communication channel TCP perform these tasks: -connection establishment by handshake (relatively slow) -division to numbered packets (transferred by IP) -error correction of packets (checksum) -acknowledgement and retransmission of packets -connection termination by handshake

UDP (User Datagram Protocol) Enables direct datagram (packet) transmission from one endpoint to another No reliability (except for data correction) -sender does not wait for acknowledgements -arrival order is not guaranteed -arrival is not guaranteed Used when speed is essential, even in cost of reliability -e.g., streaming media, games, Internet telephony, etc.

Ports A computer may have several applications that communicate with applications on remote computers through the same physical connection to the network When receiving a packet, how can the computer tell which application is the destination? Solution: each channel endpoint is assigned a unique port that is known to both the computer and the other endpoint

Ports (cont) Thus, an endpoint application on the Internet is identified by -A host name → 32 bits IP-address -A 16 bits port Q: Why don’t we specify the port in a Web browser?

Known Ports Some known ports are -20, 21: FTP -23: TELNET -25: SMTP -110: POP3 -80: HTTP -119: NNTP Client Application web browser mail client

Sockets A socket is a construct that represents one end-point of a two-way communication channel between two programs running on the network Using sockets, the OS provides processes a file-like access to the channel -i.e., sockets are allocated a file descriptor, and processes can access (read/write) the socket by specifying that descriptor A specific socket is identified by the machine's IP and a port within that machine

Sockets (cont) A socket stores the IP and port number of the other end- point computer of the channel When writing to a socket, the written bytes are sent to the other computer and port (e.g., over TCP/IP) -That is, remote IP and port are attached to the packets When OS receives packets on the network, it uses their destination port to decide which socket should get the received bytes

Client-Server Model A common paradigm for distributed applications Asymmetry in connection establishment: -Server waits for client requests (daemon) at a well known address (IP+port) -Connection is established upon client request Once the connection is made, it can be either symmetric (TELNET) or asymmetric (HTTP) For example: Web servers and browsers

Client-Server Interaction

Java Sockets Low-Level Networking

Java Sockets Java wraps OS sockets (over TCP) by the objects of class java.net.Socket new Socket(String remoteHost, int remotePort) creates a TCP socket and connects it to the remote host on the remote port (hand shake) Write and read using streams: - InputStream getInputStream() - OutputStream getOutputStream()

A Socket Example import java.net.*; import java.io.*; public class SimpleSocket { public static void main(String[] args) throws IOException {... next slide... }

Socket socket = new Socket(" 80); InputStream istream = socket.getInputStream(); OutputStream ostream = socket.getOutputStream(); String request = "GET /~dbi/admin.html HTTP/1.1\r\n" + "Host: + "Connection: close\r\n\r\n"; ostream.write(request.getBytes()); byte[] response = new byte[4096]; int bytesRead = -1; while ((bytesRead = istream.read(response)) >= 0) { System.out.write(response, 0, bytesRead); } socket.close();

Java ServerSocket ServerSocket represents a socket that listens and waits for requests from clients Construction: - new ServerSocket(int port) -Why do want to specify the port? Listen and accept incoming connections - Socket accept() -returns a new socket (with a new port) for the new channel -blocks until connection is made

public class EchoServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8000); Socket socket = null; while (true) { try {... next slide... } catch (IOException exp) {... } finally { try {if (!socket.isClosed()) socket.close(); } catch (IOException e) {} } }}}

socket = serverSocket.accept(); String clientName = socket.getInetAddress().getHostName(); BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintStream writer = new PrintStream(socket.getOutputStream()); writer.println("Hello " + clientName + "!"); writer.flush(); String lineRead = null; while ((lineRead = reader.readLine()) != null) { writer.println("You wrote: " + lineRead); writer.flush(); }

Accepting Connections Usually, the accept() method is executed within an infinite loop -i.e., while(true){...} Whenever accept() returns, a new thread is launched to handle that interaction Hence, the server can handle several requests concurrently

Timeout You can set timeout values to these blocking methods: - read() of Socket - accept() of ServerSocket Use the method setSoTimeout(milliseconds) If timeout is reached before the method returns, java.net.SocketTimeoutException is thrown

Java Sockets and HTTP

HTTP Message Structure A HTTP message has the following structure: Request/Status-Line \r\n Header1: value1 \r\n Header2: value2 \r\n... HeaderN: valueN \r\n \r\n Message-Body

Reading HTTP Messages Several ways to interpret the bytes of the body -Binary: images, compressed files, class files,... -Text: ASCII, Latin-1, UTF-8,... Commonly, applications parse the headers of the message, and process the body according to the information supplied by the headers -E.g., Content-Type, Content-Encoding, Transfer- Encoding

An Example

Parsing the Headers So how are the headers themselves are represented? Answer: The headers of a HTTP message must be in US-ASCII format (1 byte per character) However, in order to parse the headers, it may be impossible to use readLine() of BufferedReader, since the body should be later read as binary bytes Hence, we convert bytes to characters

Socket socket = new Socket(argv[0], 80); InputStream istream = socket.getInputStream(); OutputStream ostream = socket.getOutputStream(); String request = "GET / HTTP/1.1\r\n" + "Host: " + argv[0] + "\r\n" + "Connection: close\r\n\r\n"; ostream.write(request.getBytes()); StringBuffer headers = new StringBuffer(); int byteRead = 0; while ( !endOfHeaders(headers) && (byteRead = istream.read()) >= 0) { headers.append((char) byteRead); } System.out.print(headers); socket.close(); Example: Extracting the Headers

public static boolean endOfHeaders(StringBuffer headers) { int lastIndex = headers.length() - 1; if (lastIndex < 3 || headers.charAt(lastIndex) != '\n') return false; return ( headers.substring(lastIndex - 3, lastIndex + 1).equals("\r\n\r\n")); } Example: Extracting the Headers (cont)

Persistent Connections According to HTTP/1.1, a server does not have to close the connection after fulfilling your request One connection (socket) can be used for several requests and responses send more requests -even while earlier responses are being transferred (pipelining) Question: how can the client know when one response ends and a new one begins? To avoid persistency, require explicitly by the header: Connection: close

URL and URLConnection High-Level Networking

Protocol Host Name Port Number File Name Reference Working with URLs URL (Uniform Resource Locator): a reference (an address) to a resource on the Internet

The Class URL The class URL is used for parsing URLs Constructing URLs: - URL w3c1 = new URL(" - URL w3c2 = new URL("http"," - URL w3c3 = new URL(w3c2, "xhtml1/"); If the string is not an absolute URL, then it is considered relative to the URL

Parsing URLs The following methods of URL can be used for parsing URLs getProtocol(), getHost(), getPort(), getPath(), getFile(), getQuery(), getRef(), getQuery()

The class URLConnection To establish the actual resource, we can use the object URLConnection obtained by url.openConnection() If the protocol of the URL is HTTP, the returned object is of class HttpURLConnection This class encapsulates all socket management and HTTP directions required to obtain the resource

public class ContentExtractor { public static void main(String[] argv) throws Exception { URL url = new URL(argv[0]); System.out.println("Host: " + url.getHost()); System.out.println("Protocol: " + url.getProtocol()); System.out.println("----"); URLConnection con = url.openConnection(); InputStream stream = con.getInputStream(); byte[] data = new byte[4096]; int bytesRead = 0; while((bytesRead=stream.read(data))>=0) { System.out.write(data,0,bytesRead); }}}

About URLConnection The life cycle of a URLConnection object has two parts: -Before actual connection establishment Connection configuration -After actual connection establishment Content retrieval Passage from the first phase to the second is implicit -A result of calling some committing methods, like getDate()

About HttpURLConnection The HttpURLConnection class encapsulates all HTTP transaction over sockets, e.g., -Content decoding -Redirection -Proxy indirection However, you can control requests by its methods - setRequestMethod, setFollowRedirects, setRequestProperty,...

Sending POST Requests In order to send POST requests with HttpURLConnection, you have to do the following: -Enable connection output: con.setDoOutput(true); -Get the output stream: con.getOutputStream() This changes the method from GET to POST -Write the message body into the stream -close the stream (important!)

URL url = new URL(" URLConnection connection = url.openConnection(); connection.setDoOutput(true); String query = "q=" + URLEncoder.encode(args[0], "UTF-8"); OutputStream out = connection.getOutputStream(); out.write(query.getBytes()); out.close(); InputStream in = connection.getInputStream(); int bytesRead = -1; byte[] response = new byte[4096]; while ((bytesRead = in.read(response)) >= 0) System.out.write(response, 0, bytesRead); in.close();

POST / HTTP/1.1 User-Agent: Java/1.5.0_01 Host: find.walla.co.il Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 Connection: keep-alive Content-type: application/x-www-form-urlencoded Content-Length: 18 q=Java+networking java SearchWalla "Java networking" Sent Headers

URLEncoder Contains a utility method encode for converting a string into an encoded format (used in URLs) To convert a string, each character is examined in turn: -Space is converted into a plus sign + - a - z, A - Z, 0 - 9,., -, * and _ remain the same. -The bytes of all special characters are replaced by hexadecimal numbers, preceded with % To decode an encoded string, use decode() of the class URLDecoder

Defining Default Proxy For reading a URL using a proxy, we run java with the environment variables for http.proxyHost and http.proxyPort set properly: java -DproxyHost=wwwproxy.huji.ac.il –DproxyPort= Another option is to set the environment variables in the program itself System.getProperties().put( "proxyHost", "wwwproxy.huji.ac.il" ); System.getProperties().put( "proxyPort", "8080" );

Not Covered: UDP Connections The URL, URLConnection, Socket and ServerSocket classes all use the TCP protocol to communicate over the network Java programs can also use UDP protocol for communication For that, use DatagramPacket, DatagramSocket, and MulticastSocket classes