Networking with Java 2.

Slides:



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

Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
Referring to Java API Specifications
Network Programming Chapter 11 Lecture 6. Networks.
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
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.
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
1 Java Networking – part I CS , Winter 2007/8.
Networking with Java. Introduction to Networking.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
Networking in Java Representation and Management of Data on the Internet.
1 Networking with Java. 2 Introduction to Networking.
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.
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
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.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
DBI Representation and Management of Data on the Internet.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
UDP vs TCP UDP Low-level, connectionless No reliability guarantee TCP Connection-oriented Not as efficient as UDP.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
Socket Programming in Java CS587x Lecture 4 Department of Computer Science Iowa State University.
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.
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.
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
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.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses.
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.
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 ( 李德成 )
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.
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
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.
Network Programming Communication between processes Many approaches:
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit9: Internet programming 1.
Java 13. Networking public class SumTest {
Object-Orientated Analysis, Design and Programming
Secure Sockets SSL (Secure Sockets Layer) is a standard security technology for establishing an encrypted link between a server and a client—typically.
Echo Networking COMP
Network Programming in Java CS 1111 Ryan Layer May 3, 2010
Lecture 21 Sockets 1 (Not in D&D) Date.
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
CSI 4118 – UNIVERSITY OF OTTAWA
Uniform Resource Locators
„Networking”.
Lecture 11 Socket Programming.
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
Uniform Resource Locators (URLs)
Uniform Resource Locators
Socket Programming 2: Application Layer.
Clients and Servers 19-Jul-19.
CS18000: Problem Solving and Object-Oriented Programming
Clients and Servers 13-Sep-19.
Presentation transcript:

Networking with Java 2

Some Terms Mentioned Last Week TCP Relatively slow but enables reliable byte-stream transmission UDP Fast unreliable datagram (packet) transmission Ports Application’s “channel address” Sockets Endpoint representation of 2-way communication channel between programs

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

Client-Server Interaction

Client-Server Interaction

Client-Server Interaction

Client-Server Interaction

Java Sever Sockets

Java Sockets – A Reminder 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()

Java ServerSocket Construction: Listen and accept incoming connections ServerSocket represents a socket that listens and waits for requests from clients Construction: new ServerSocket(int port) Why do we 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 Read more about ServerSocket Class

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(); } chars bytes run the example

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 (not in our example) Hence, the server can handle several requests concurrently

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

SimpleSocket – A Reminder  Socket socket = new Socket("www.cs.huji.ac.il", 80);     InputStream istream = socket.getInputStream();     OutputStream ostream = socket.getOutputStream();     String request =        "GET /~dbi/admin.html HTTP/1.1\r\n"  +        "Host: www.cs.huji.ac.il\r\n" +        "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();

Get Vs. Post Get Post Returns the content of the requested URL Usually a static resource Post A block of data is sent with the request Usually a program or a form

ContentExtractor – A Reminder 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("----");     HttpURLConnection 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); }}}

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 output stream close the output stream (important!)

POST Example - SearchWalla URL url = new URL("http://find.walla.co.il/"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); String query = "q=" + URLEncoder.encode(argv[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();

java SearchWalla "Java networking" Sent Headers java SearchWalla "Java networking" 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

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 –Dhttp.proxyHost=wwwproxy.huji.ac.il –Dhttp.proxyPort=8080 ... Another option is to set the environment variables in the program itself System.getProperties().put( “http.proxyHost", "wwwproxy.huji.ac.il" ); System.getProperties().put( “http.proxyPort", "8080" ); Read more about networking with proxies

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