SlideShare a Scribd company logo
Java Network Programming Tushar B. Kute Assistant Professor Department of Information Technology, Sandip Institute of Technology and Research Centre, Nashik.
Agenda Networking Basics TCP, UDP, Ports, DNS, Client-Server Model TCP/IP in Java Socket Programming URL The java classes:  URL, URLConnection Datagram Programming
“ The Network is Computer” Internet Server PC client Local Area Network PDA
Increased demand for Internet applications To take advantage of opportunities presented by the Internet, businesses are continuously seeking new and innovative ways and means for offering their services via the Internet. This created a huge demand for software designers with skills to create new Internet-enabled applications or migrate existing/legacy applications on the Internet platform. Object-oriented Java technologies—Sockets, threads, RMI, clustering, Web services-- have emerged as leading solutions for creating portable, efficient, and maintainable large and complex Internet applications.
Elements of C-S Computing Network Request Result a client, a server, and network Client Server Client machine Server machine
Networking Basics  Computers running on the Internet communicate with each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP)
DNS - Domain name system  The  Domain Name system  (DNS) associates various sorts of information with so-called domain names. Most importantly, it serves as the "phone book" for the Internet by translating human-readable computer hostnames, e.g.  www.example.com , into the IP addresses, e.g.  208.77.188.166 , that networking equipment needs to deliver information. It also stores other information such as the list of mail exchange servers that accept email for a given domain.
Understanding Ports The TCP and UDP protocols use  ports  to map incoming data to a particular  process  running on a computer. server P o r t Client TCP TCP or UDP port port port port app app app app port# data Data Packet
Understanding Ports Port is represented by a positive (16-bit) integer value Some ports have been reserved to support common/well known services: ftp  21/tcp telnet 23/tcp smtp 25/tcp login 513/tcp User level process/services generally use port number value >= 1024
Sockets Sockets provide an interface for programming networks at the transport layer. Network communication using Sockets is very much similar to performing file I/O In fact, socket handle is treated like file handle. The streams used in file I/O operation are also applicable to socket-based I/O Socket-based communication is programming language independent. That means, a socket program written in Java language can also communicate to a program written in Java or non-Java socket program.
Socket Communication A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request. server Client Connection request port
Socket Communication If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client. server Client Connection port port port
Transmission Control Protocol A connection-based protocol that provides a reliable flow of data between two computers.  Provides a point-to-point channel for applications that require reliable communications.  The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel  Guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent. Otherwise, an error is reported.
User Datagram Protocol A protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP and is not reliable: 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 Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined.  The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application.
Ports – Cont. Port numbers range from 0 to 65,535 (16-bit) Ports 0 - 1023 are called  well-known ports.  They are reserved for use by well-known services: 20, 21: FTP 23: TELNET 25: SMTP 110: POP3 80: HTTP
Networking Classes in the JDK Through the classes in java.net, Java programs can use TCP or UDP to communicate over the Internet. The  URL, URLConnection, Socket,  and  ServerSocket  classes all use TCP to communicate over the network. The  DatagramPacket, DatagramSocket , and  MulticastSocket  classes are for use with UDP.
TCP/IP in Java Accessing TCP/IP from Java is straightforward. The main functionality is in the following classes: java.net.InetAddress  : Represents an IP address (either IPv4 or IPv6) and has methods for performing DNS lookup (next slide). java.net.Socket  : Represents a TCP socket. java.net.ServerSocket  : Represents a server socket which is capable of waiting for requests from clients.
InetAddress The InetAddress class is used to encapsulate both the numerical IP address and the domain name for that address.  We interact with this class by using the name of an IP host, which is more convenient and understandable than its IP address.  The InetAddress class hides the number inside.
Factory Methods static InetAddress getLocalHost( ) throws UnknownHostException static InetAddress getByName(String hostName) throws UnknownHostException static InetAddress[ ] getAllByName(String  hostName) throws UnknownHostException
Example: class InetAddressTest { public static void main(String args[]) throws UnknownHostException { InetAddress Address = InetAddress.getLocalHost(); System.out.println(Address); Address = InetAddress.getByName(&quot;www.tusharkute.com&quot;); System.out.println(Address); InetAddress SW[] = InetAddress.getAllByName(&quot;www.yahoo.com&quot;); for (int i=0; i<SW.length; i++)     System.out.println(SW[i]); } }
Instance Methods class InetAddressTest1 { public static void main(String args[]) throws UnknownHostException { InetAddress Address =    InetAddress.getByName(&quot;www.google.com&quot;); System.out.println(Address.getHostAddress()); System.out.println(Address.getHostName()); if(Address.isMulticastAddress())   System.out.println(&quot;It is multicast address&quot;); } }
Sockets and Java Socket Classes A socket is an endpoint of a two-way communication link between two programs running on the network.  A socket is bound to a port number so that the TCP layer can identify the application that data destined to be sent. Java’s .net package provides two classes: Socket  – for implementing a client ServerSocket  – for implementing a server
Java Sockets ServerSocket(1234) Socket(“128.250.25.158”, 1234) Output/write stream Input/read stream It can be host_name like “books.google.com” Client Server
Client Sockets Java wraps OS sockets (over TCP) by the objects of class  java.net.Socket 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()
Constructors Socket(String  remoteHost , int  remotePort )   Socket(InetAddress ip, int  remotePort )
Instance   Methods InetAddress getInetAddress( ) int getPort( ) int getLocalPort( ) InputStream getInputStream( ) OutputStream getOutputStream( ) void close( )
Implementing a Client 1. Create a Socket Object: client = new Socket( server, port_id ); 2. Create I/O streams for communicating with the server. is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 3. Perform I/O or communication with the server: Receive data from the server:  String line = is.readLine();  Send data to the server:  os.writeBytes(&quot;Hello\n&quot;); 4. Close the socket when done:  client.close();
Example: Whois server class Whois  { public static void main(String args[  ]) throws Exception  { int c; Socket s = new Socket(&quot;internic.net&quot;, 43); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); String str=&quot;www.google.com&quot;; byte buf[] = str.getBytes(); out.write(buf); while ((c = in.read()) != -1)  System.out.print((char) c); s.close(); } }
Example: Time server public class Daytime { public static void main(String[] args) throws Exception { Socket theSocket = new Socket(&quot;time.nist.gov&quot;, 13); InputStream timeStream = theSocket.getInputStream( ); StringBuffer time = new StringBuffer( ); int c; while ((c = timeStream.read( )) != -1)  time.append((char) c); String timeString = time.toString( ).trim( );  System.out.println(&quot;It is &quot; + timeString + &quot; at &quot; + &quot;local host&quot;); } }
ServerSocket This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester.  A server socket is technically not a socket: when a client connects to a server socket, a TCP connection is made, and a (normal) socket is created for each end point.
Constructors ServerSocket (int port)  throws BindException, IOException ServerSocket (int port, int maxQueue)  throws BindException, IOException ServerSocket (int port, int maxQ, InetAddress ip)  throws IOException
Implementing a Server Open the Server Socket: ServerSocket server;  DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT ); Wait for the Client Request: Socket client = server.accept(); Create I/O streams for communicating to the client is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream(client.getOutputStream()); Perform communication with client  Receive from client: String line = is.readLine();  Send to client: os.writeBytes(&quot;Hello\n&quot;); Close sockets:  client.close();
Accepting Connections Usually, the  accept()   method is executed within an infinite loop i.e.,  while(true) {...} The accept method returns a new socket (with a new port) for the new channel. It blocks   until connection is made. Syntax: Socket accept() throws IOException
Client-Server Interaction via TCP
Examples EchoDemoServer EchoDemoClient
URL -  Uniform Resource Locator   URL is a reference (an address) to a resource on the Internet.  A resource can be a file, a database query and more. URLs are just a subset of the more general concept of Uniform Resource Identifiers (URIs) which are meant to describe all points in the information space http://www.javapassion.com:80/javaintro/index.html#Networking_A Protocol Host Name Port Number Path & File Name Reference
Class  URL Class URL represents a Uniform Resource Locator, a pointer to a &quot;resource&quot; on the World Wide Web.  We distinguish between: Absolute URL - contains all of the information necessary to reach the resource. Relative URL - contains only enough information to reach the resource relative to (or in the context of) another URL.
Constructors URL(String urlSpecifier) URL(URL urlObj, String urlSpecifier) URL(String protName, String hostName, int port, String path) URL(String protName, String hostName, String path)
Example class URLDemo { public static void main(String args[]) throws MalformedURLException { URL hp = new URL (&quot; http://content- ind.cricinfo.com/ci/content/current/story/news.html &quot;); System.out.println(&quot;Protocol: &quot; + hp.getProtocol()); System.out.println(&quot;Port: &quot; + hp.getPort()); System.out.println(&quot;Host: &quot; + hp.getHost()); System.out.println(&quot;File: &quot; + hp.getFile()); System.out.println(&quot;Ext:&quot; + hp.toExternalForm()); } }
Output Protocol: http Port: -1 Host: content-ind.cricinfo.com File: /ci/content/current/story/news.html Ext:http://content-ind.cricinfo.com/ci/content/current/story/news.html
URLConnection URLConnection is an abstract class that represents an active connection to a resource specified by a URL.  The URLConnection class has two different but related purposes. First, it provides more control over the interaction with a server (especially an HTTP server) than the URL class. With a URLConnection, we can inspect the header sent by the server and respond accordingly. We can set the header fields used in the client request. We can use a URLConnection to download binary files.  Finally, a URLConnection lets us send data back to a web server with POST or PUT and use other HTTP request methods.
Process Construct a URL object. Invoke the URL object's openConnection( ) method to retrieve a URLConnection object for that URL. Configure the URLConnection. Read the header fields. Get an input stream and read data. Get an output stream and write data. Close the connection.
Reading Data from Server Construct a URL object. Invoke the URL object's openConnection( ) method to retrieve a URLConnection object for that URL. Invoke the URLConnection's getInputStream( ) method. Read from the input stream using the usual stream API. The getInputStream() method returns a generic InputStream that lets you read and parse the data that the server sends. public InputStream getInputStream( )
Example public class SourceViewer { public static void main (String[] args) {   if  (args.length > 0) { try { //Open the URLConnection for reading URL u = new URL(args[0]); URLConnection uc = u.openConnection( ); InputStream raw = uc.getInputStream( ); InputStream buffer = new BufferedInputStream(raw);  // chain the InputStream to a Reader Reader r = new InputStreamReader(buffer); int c; while ((c = r.read( )) != -1) { System.out.print((char) c); }  } catch (MalformedURLException ex) { System.err.println(args[0] + &quot; is not a parseable URL&quot;); } catch (IOException ex) { System.err.println(ex); } } } }
import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL yahoo = new URL(&quot;http://www.yahoo.com/&quot;); URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null)  System.out.println(inputLine); in.close(); } } URLConnection Example
Difference between URL and URLConnection URLConnection provides access to the HTTP header. URLConnection can configure the request parameters sent to the server. URLConnection can write data to the server as well as read data from the server.
Header Information HTTP/1.1 200 OK Date: Mon, 18 Oct 1999 20:06:48 GMT Server: Apache/1.3.4 (Unix) PHP/3.0.6 mod_perl/1.17 Last-Modified: Mon, 18 Oct 1999 12:58:21 GMT ETag: &quot;1e05f2-89bb-380b196d&quot; Accept-Ranges: bytes Content-Length: 35259 Connection: close Content-Type: text/html
Methods public String getContentType( ) public int getContentLength( ) public long getDate( ) public long getExpiration( ) public long getLastModified( )
Example public class HeaderViewer  { public static void main(String args[])  { try  { URL u = new URL(&quot;http://www.rediffmail.com/index.html&quot;); URLConnection uc = u.openConnection( ); System.out.println(&quot;Content-type: &quot; +  uc.getContentType( )); System.out.println(&quot;Content-encoding: &quot;  + uc.getContentEncoding( )); System.out.println(&quot;Date: &quot; + new Date(uc.getDate( ))); System.out.println(&quot;Last modified: &quot;  + new Date(uc.getLastModified( ))); System.out.println(&quot;Expiration date: &quot;  + new Date(uc.getExpiration( ))); System.out.println(&quot;Content-length: &quot; +  uc.getContentLength( )); }  // end try catch (MalformedURLException ex)  { System.out.println(&quot;I can't understand this URL..&quot;); } catch (IOException ex)  { System.err.println(ex); }  System.out.println( );  }  // end main }  // end HeaderViewer
Sample Output Sample output: Content-type: text/htmlContent-encoding: nullDate: Mon Oct 18 13:54:52 PDT 1999Last modified: Sat Oct 16 07:54:02 PDT 1999Expiration date: Wed Dec 31 16:00:00 PST 1969   Content-length: -1 Sample output for: http://www.oreilly.com/graphics/space.gif   Content-type: image/gifContent-encoding: nullDate: Mon Oct 18 14:00:07 PDT 1999Last modified: Thu Jan 09 12:05:11 PST 1997Expiration date: Wed Dec 31 16:00:00 PST 1969   Content-length: 57
Retrieving Header field public String getHeaderField(String name) Example: String contentType = uc.getHeaderField(&quot;content-type&quot;); String contentEncoding = uc.getHeaderField(&quot;content-encoding&quot;)); String data = uc.getHeaderField(&quot;date&quot;); String expires = uc.getHeaderField(&quot;expires&quot;); String contentLength = uc.getHeaderField(&quot;Content-length&quot;);
Datagrams A  datagram  is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.  The  java.net  package contains three classes to help you write Java programs that use datagrams to send and receive packets over the network:  DatagramSocket and DatagramPacket
TCP vs. UDP No. TCP UDP 1 This Connection oriented protocol  This is connection-less protocol 2 The TCP connection is byte stream The UDP connection is a message stream 3 It does not support multicasting and broadcasting It supports broadcasting 4 It provides error control and flow control The error control and flow control is not provided 5 TCP supports full duplex transmission UDP does not support full duplex transmission 6 It is reliable service of data transmission This is an unreliable service of data transmission  7 The TCP packet is called as segment The UDP packet is called as user datagram.
UDP in Java DatagramPacket DatagramSocket
Receiving DatagramPacket public DatagramPacket(byte[ ] buffer, int length)  public DatagramPacket(byte[ ] buffer, int offset, int length) Example:  byte[ ] buffer = new byte[8192]; DatagramPacket dp = new  DatagramPacket(buffer, buffer.length);
Sending Datagrams public DatagramPacket(byte[ ] data, int length, InetAddress destination, int port) public DatagramPacket(byte[ ] data, int offset, int length,  InetAddress destination, int port)
DatagramSocket public DatagramSocket( ) throws  SocketException public DatagramSocket(int port) throws  SocketException public DatagramSocket(int port, InetAddress interface) throws SocketException
Sending and Receiving Packets  public void send(DatagramPacket dp) throws  IOException public void receive(DatagramPacket dp) throws IOException
Example : UDPServer UDPClient
References 1. Java Network Programming, 3rd Edition, By Elliotte Rusty Harold, O'Reilly, October 2004 Chapter 2: Basic Networking Concepts Chapter 7: URLs and URIs Chapter 9: Sockets for Clients Chapter 10: Sockets for Servers Chapter 13: UDP Datagrams and Sockets Chapter 15: URL Connections 2. Java 2 the Complete Reference , Fifth Edition by Herbert Schildt, 2001, Osborne McGraw Hill. Chapter 18: Networking
References 3. Learning Java, 3rd Edition, By Jonathan Knudsen, Patrick Niemeyer, O'Reilly, May 2005 Chapter 13: Network Programming 4. A Laboratory Manual for Java Programming (1526) , by Maharashtra State Board of Technical Education, Mumbai, 2004
Thank You [email_address]

More Related Content

PPTX
IP classes
PPTX
Tcp IP Model
PPT
Network programming in Java
PPT
Overview of TCP IP
PPTX
Introduction Of C++
PPT
Basic networking hardware: Switch : Router : Hub : Bridge : Gateway : Bus : C...
PPT
Addressing in Computer Networks
IP classes
Tcp IP Model
Network programming in Java
Overview of TCP IP
Introduction Of C++
Basic networking hardware: Switch : Router : Hub : Bridge : Gateway : Bus : C...
Addressing in Computer Networks

What's hot (20)

PPTX
Computer networks network layer,routing
PPT
user defined function
PDF
Function in C
PPTX
IPv4 and IPv6
PDF
What is Socket Programming in Python | Edureka
PPTX
Introduction to ns3
PPTX
Client server chat application
PPT
Ipv4 ppt
PPT
Ccna1 presentation
PPTX
My ppt..priya
PDF
Chapter 10 - Multimedia Over Atm
PPTX
Interfacing With High Level Programming Language
PDF
Unit II -Mobile telecommunication systems
PPT
PPTX
The string class
PDF
Tutorial ns 3-tutorial-slides
DOC
Moc mtc
PPTX
Broadband isdn
PPT
Ch6 1 v1
PPTX
StringBuffer.pptx
Computer networks network layer,routing
user defined function
Function in C
IPv4 and IPv6
What is Socket Programming in Python | Edureka
Introduction to ns3
Client server chat application
Ipv4 ppt
Ccna1 presentation
My ppt..priya
Chapter 10 - Multimedia Over Atm
Interfacing With High Level Programming Language
Unit II -Mobile telecommunication systems
The string class
Tutorial ns 3-tutorial-slides
Moc mtc
Broadband isdn
Ch6 1 v1
StringBuffer.pptx
Ad

Viewers also liked (7)

PPTX
JAVA Networking
PPTX
PPT
Java networking
PPTX
Advance Java-Network Programming
PPTX
Networking in Java
PPTX
Digital wallet
PDF
Apple Pay's Obvious Value Proposition
JAVA Networking
Java networking
Advance Java-Network Programming
Networking in Java
Digital wallet
Apple Pay's Obvious Value Proposition
Ad

Similar to Network Programming in Java (20)

PPT
Network programming in Java
PPT
Md13 networking
PPT
Unit 8 Java
PPTX
5_6278455688045789623.pptx
PDF
28 networking
PPTX
Networking.pptx
PPTX
PPT
Sockets
PPT
Networking & Socket Programming In Java
PPT
Socket Programming - nitish nagar
PPTX
Java socket programming
PDF
Socket programming
PPT
Networking Java Socket Programming
PDF
Socket Programming by Rajkumar Buyya
PDF
javanetworking
PDF
Chap 1 Network Theory & Java Overview
PPT
Socket Programming in Java.ppt yeh haii
DOCX
Mail Server Project Report
PDF
Networking
PDF
Networking Basics1ofjavaprogramming.pptx.pdf
Network programming in Java
Md13 networking
Unit 8 Java
5_6278455688045789623.pptx
28 networking
Networking.pptx
Sockets
Networking & Socket Programming In Java
Socket Programming - nitish nagar
Java socket programming
Socket programming
Networking Java Socket Programming
Socket Programming by Rajkumar Buyya
javanetworking
Chap 1 Network Theory & Java Overview
Socket Programming in Java.ppt yeh haii
Mail Server Project Report
Networking
Networking Basics1ofjavaprogramming.pptx.pdf

More from Tushar B Kute (20)

PDF
ॲलन ट्युरिंग: कृत्रिम बुद्धिमत्तेचा अग्रदूत - लेखक: तुषार भ. कुटे.pdf
PDF
Apache Pig: A big data processor
PDF
01 Introduction to Android
PDF
Ubuntu OS and it's Flavours
PDF
Install Drupal in Ubuntu by Tushar B. Kute
PDF
Install Wordpress in Ubuntu Linux by Tushar B. Kute
PDF
Share File easily between computers using sftp
PDF
Signal Handling in Linux
PDF
Implementation of FIFO in Linux
PDF
Implementation of Pipe in Linux
PDF
Basic Multithreading using Posix Threads
PDF
Part 04 Creating a System Call in Linux
PDF
Part 03 File System Implementation in Linux
PDF
Part 02 Linux Kernel Module Programming
PDF
Part 01 Linux Kernel Compilation (Ubuntu)
PDF
Open source applications softwares
PDF
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
PDF
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
PDF
Technical blog by Engineering Students of Sandip Foundation, itsitrc
PDF
Chapter 01 Introduction to Java by Tushar B Kute
ॲलन ट्युरिंग: कृत्रिम बुद्धिमत्तेचा अग्रदूत - लेखक: तुषार भ. कुटे.pdf
Apache Pig: A big data processor
01 Introduction to Android
Ubuntu OS and it's Flavours
Install Drupal in Ubuntu by Tushar B. Kute
Install Wordpress in Ubuntu Linux by Tushar B. Kute
Share File easily between computers using sftp
Signal Handling in Linux
Implementation of FIFO in Linux
Implementation of Pipe in Linux
Basic Multithreading using Posix Threads
Part 04 Creating a System Call in Linux
Part 03 File System Implementation in Linux
Part 02 Linux Kernel Module Programming
Part 01 Linux Kernel Compilation (Ubuntu)
Open source applications softwares
Introduction to Ubuntu Edge Operating System (Ubuntu Touch)
Unit 6 Operating System TEIT Savitribai Phule Pune University by Tushar B Kute
Technical blog by Engineering Students of Sandip Foundation, itsitrc
Chapter 01 Introduction to Java by Tushar B Kute

Recently uploaded (20)

PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Institutional Correction lecture only . . .
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Lesson notes of climatology university.
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
master seminar digital applications in india
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
O7-L3 Supply Chain Operations - ICLT Program
Anesthesia in Laparoscopic Surgery in India
Computing-Curriculum for Schools in Ghana
Institutional Correction lecture only . . .
Pharma ospi slides which help in ospi learning
Lesson notes of climatology university.
Microbial diseases, their pathogenesis and prophylaxis
STATICS OF THE RIGID BODIES Hibbelers.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
master seminar digital applications in india
TR - Agricultural Crops Production NC III.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Basic Mud Logging Guide for educational purpose
Final Presentation General Medicine 03-08-2024.pptx
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Sports Quiz easy sports quiz sports quiz
O5-L3 Freight Transport Ops (International) V1.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
human mycosis Human fungal infections are called human mycosis..pptx

Network Programming in Java

  • 1. Java Network Programming Tushar B. Kute Assistant Professor Department of Information Technology, Sandip Institute of Technology and Research Centre, Nashik.
  • 2. Agenda Networking Basics TCP, UDP, Ports, DNS, Client-Server Model TCP/IP in Java Socket Programming URL The java classes: URL, URLConnection Datagram Programming
  • 3. “ The Network is Computer” Internet Server PC client Local Area Network PDA
  • 4. Increased demand for Internet applications To take advantage of opportunities presented by the Internet, businesses are continuously seeking new and innovative ways and means for offering their services via the Internet. This created a huge demand for software designers with skills to create new Internet-enabled applications or migrate existing/legacy applications on the Internet platform. Object-oriented Java technologies—Sockets, threads, RMI, clustering, Web services-- have emerged as leading solutions for creating portable, efficient, and maintainable large and complex Internet applications.
  • 5. Elements of C-S Computing Network Request Result a client, a server, and network Client Server Client machine Server machine
  • 6. Networking Basics Computers running on the Internet communicate with each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP)
  • 7. DNS - Domain name system The Domain Name system (DNS) associates various sorts of information with so-called domain names. Most importantly, it serves as the &quot;phone book&quot; for the Internet by translating human-readable computer hostnames, e.g. www.example.com , into the IP addresses, e.g. 208.77.188.166 , that networking equipment needs to deliver information. It also stores other information such as the list of mail exchange servers that accept email for a given domain.
  • 8. Understanding Ports The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. server P o r t Client TCP TCP or UDP port port port port app app app app port# data Data Packet
  • 9. Understanding Ports Port is represented by a positive (16-bit) integer value Some ports have been reserved to support common/well known services: ftp 21/tcp telnet 23/tcp smtp 25/tcp login 513/tcp User level process/services generally use port number value >= 1024
  • 10. Sockets Sockets provide an interface for programming networks at the transport layer. Network communication using Sockets is very much similar to performing file I/O In fact, socket handle is treated like file handle. The streams used in file I/O operation are also applicable to socket-based I/O Socket-based communication is programming language independent. That means, a socket program written in Java language can also communicate to a program written in Java or non-Java socket program.
  • 11. Socket Communication A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request. server Client Connection request port
  • 12. Socket Communication If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bounds to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client. server Client Connection port port port
  • 13. Transmission Control Protocol A connection-based protocol that provides a reliable flow of data between two computers. Provides a point-to-point channel for applications that require reliable communications. The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel Guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent. Otherwise, an error is reported.
  • 14. User Datagram Protocol A protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP and is not reliable: 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.
  • 15. Ports Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application.
  • 16. Ports – Cont. Port numbers range from 0 to 65,535 (16-bit) Ports 0 - 1023 are called well-known ports. They are reserved for use by well-known services: 20, 21: FTP 23: TELNET 25: SMTP 110: POP3 80: HTTP
  • 17. Networking Classes in the JDK Through the classes in java.net, Java programs can use TCP or UDP to communicate over the Internet. The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate over the network. The DatagramPacket, DatagramSocket , and MulticastSocket classes are for use with UDP.
  • 18. TCP/IP in Java Accessing TCP/IP from Java is straightforward. The main functionality is in the following classes: java.net.InetAddress : Represents an IP address (either IPv4 or IPv6) and has methods for performing DNS lookup (next slide). java.net.Socket : Represents a TCP socket. java.net.ServerSocket : Represents a server socket which is capable of waiting for requests from clients.
  • 19. InetAddress The InetAddress class is used to encapsulate both the numerical IP address and the domain name for that address. We interact with this class by using the name of an IP host, which is more convenient and understandable than its IP address. The InetAddress class hides the number inside.
  • 20. Factory Methods static InetAddress getLocalHost( ) throws UnknownHostException static InetAddress getByName(String hostName) throws UnknownHostException static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException
  • 21. Example: class InetAddressTest { public static void main(String args[]) throws UnknownHostException { InetAddress Address = InetAddress.getLocalHost(); System.out.println(Address); Address = InetAddress.getByName(&quot;www.tusharkute.com&quot;); System.out.println(Address); InetAddress SW[] = InetAddress.getAllByName(&quot;www.yahoo.com&quot;); for (int i=0; i<SW.length; i++) System.out.println(SW[i]); } }
  • 22. Instance Methods class InetAddressTest1 { public static void main(String args[]) throws UnknownHostException { InetAddress Address = InetAddress.getByName(&quot;www.google.com&quot;); System.out.println(Address.getHostAddress()); System.out.println(Address.getHostName()); if(Address.isMulticastAddress()) System.out.println(&quot;It is multicast address&quot;); } }
  • 23. Sockets and Java Socket Classes A socket is an endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data destined to be sent. Java’s .net package provides two classes: Socket – for implementing a client ServerSocket – for implementing a server
  • 24. Java Sockets ServerSocket(1234) Socket(“128.250.25.158”, 1234) Output/write stream Input/read stream It can be host_name like “books.google.com” Client Server
  • 25. Client Sockets Java wraps OS sockets (over TCP) by the objects of class java.net.Socket 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()
  • 26. Constructors Socket(String remoteHost , int remotePort ) Socket(InetAddress ip, int remotePort )
  • 27. Instance Methods InetAddress getInetAddress( ) int getPort( ) int getLocalPort( ) InputStream getInputStream( ) OutputStream getOutputStream( ) void close( )
  • 28. Implementing a Client 1. Create a Socket Object: client = new Socket( server, port_id ); 2. Create I/O streams for communicating with the server. is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 3. Perform I/O or communication with the server: Receive data from the server: String line = is.readLine(); Send data to the server: os.writeBytes(&quot;Hello\n&quot;); 4. Close the socket when done: client.close();
  • 29. Example: Whois server class Whois { public static void main(String args[ ]) throws Exception { int c; Socket s = new Socket(&quot;internic.net&quot;, 43); InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); String str=&quot;www.google.com&quot;; byte buf[] = str.getBytes(); out.write(buf); while ((c = in.read()) != -1) System.out.print((char) c); s.close(); } }
  • 30. Example: Time server public class Daytime { public static void main(String[] args) throws Exception { Socket theSocket = new Socket(&quot;time.nist.gov&quot;, 13); InputStream timeStream = theSocket.getInputStream( ); StringBuffer time = new StringBuffer( ); int c; while ((c = timeStream.read( )) != -1) time.append((char) c); String timeString = time.toString( ).trim( ); System.out.println(&quot;It is &quot; + timeString + &quot; at &quot; + &quot;local host&quot;); } }
  • 31. ServerSocket This class implements server sockets. A server socket waits for requests to come in over the network. It performs some operation based on that request, and then possibly returns a result to the requester. A server socket is technically not a socket: when a client connects to a server socket, a TCP connection is made, and a (normal) socket is created for each end point.
  • 32. Constructors ServerSocket (int port) throws BindException, IOException ServerSocket (int port, int maxQueue) throws BindException, IOException ServerSocket (int port, int maxQ, InetAddress ip) throws IOException
  • 33. Implementing a Server Open the Server Socket: ServerSocket server; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT ); Wait for the Client Request: Socket client = server.accept(); Create I/O streams for communicating to the client is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream(client.getOutputStream()); Perform communication with client Receive from client: String line = is.readLine(); Send to client: os.writeBytes(&quot;Hello\n&quot;); Close sockets: client.close();
  • 34. Accepting Connections Usually, the accept() method is executed within an infinite loop i.e., while(true) {...} The accept method returns a new socket (with a new port) for the new channel. It blocks until connection is made. Syntax: Socket accept() throws IOException
  • 37. URL - Uniform Resource Locator URL is a reference (an address) to a resource on the Internet. A resource can be a file, a database query and more. URLs are just a subset of the more general concept of Uniform Resource Identifiers (URIs) which are meant to describe all points in the information space http://www.javapassion.com:80/javaintro/index.html#Networking_A Protocol Host Name Port Number Path & File Name Reference
  • 38. Class URL Class URL represents a Uniform Resource Locator, a pointer to a &quot;resource&quot; on the World Wide Web. We distinguish between: Absolute URL - contains all of the information necessary to reach the resource. Relative URL - contains only enough information to reach the resource relative to (or in the context of) another URL.
  • 39. Constructors URL(String urlSpecifier) URL(URL urlObj, String urlSpecifier) URL(String protName, String hostName, int port, String path) URL(String protName, String hostName, String path)
  • 40. Example class URLDemo { public static void main(String args[]) throws MalformedURLException { URL hp = new URL (&quot; http://content- ind.cricinfo.com/ci/content/current/story/news.html &quot;); System.out.println(&quot;Protocol: &quot; + hp.getProtocol()); System.out.println(&quot;Port: &quot; + hp.getPort()); System.out.println(&quot;Host: &quot; + hp.getHost()); System.out.println(&quot;File: &quot; + hp.getFile()); System.out.println(&quot;Ext:&quot; + hp.toExternalForm()); } }
  • 41. Output Protocol: http Port: -1 Host: content-ind.cricinfo.com File: /ci/content/current/story/news.html Ext:http://content-ind.cricinfo.com/ci/content/current/story/news.html
  • 42. URLConnection URLConnection is an abstract class that represents an active connection to a resource specified by a URL. The URLConnection class has two different but related purposes. First, it provides more control over the interaction with a server (especially an HTTP server) than the URL class. With a URLConnection, we can inspect the header sent by the server and respond accordingly. We can set the header fields used in the client request. We can use a URLConnection to download binary files. Finally, a URLConnection lets us send data back to a web server with POST or PUT and use other HTTP request methods.
  • 43. Process Construct a URL object. Invoke the URL object's openConnection( ) method to retrieve a URLConnection object for that URL. Configure the URLConnection. Read the header fields. Get an input stream and read data. Get an output stream and write data. Close the connection.
  • 44. Reading Data from Server Construct a URL object. Invoke the URL object's openConnection( ) method to retrieve a URLConnection object for that URL. Invoke the URLConnection's getInputStream( ) method. Read from the input stream using the usual stream API. The getInputStream() method returns a generic InputStream that lets you read and parse the data that the server sends. public InputStream getInputStream( )
  • 45. Example public class SourceViewer { public static void main (String[] args) { if (args.length > 0) { try { //Open the URLConnection for reading URL u = new URL(args[0]); URLConnection uc = u.openConnection( ); InputStream raw = uc.getInputStream( ); InputStream buffer = new BufferedInputStream(raw); // chain the InputStream to a Reader Reader r = new InputStreamReader(buffer); int c; while ((c = r.read( )) != -1) { System.out.print((char) c); } } catch (MalformedURLException ex) { System.err.println(args[0] + &quot; is not a parseable URL&quot;); } catch (IOException ex) { System.err.println(ex); } } } }
  • 46. import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL yahoo = new URL(&quot;http://www.yahoo.com/&quot;); URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } } URLConnection Example
  • 47. Difference between URL and URLConnection URLConnection provides access to the HTTP header. URLConnection can configure the request parameters sent to the server. URLConnection can write data to the server as well as read data from the server.
  • 48. Header Information HTTP/1.1 200 OK Date: Mon, 18 Oct 1999 20:06:48 GMT Server: Apache/1.3.4 (Unix) PHP/3.0.6 mod_perl/1.17 Last-Modified: Mon, 18 Oct 1999 12:58:21 GMT ETag: &quot;1e05f2-89bb-380b196d&quot; Accept-Ranges: bytes Content-Length: 35259 Connection: close Content-Type: text/html
  • 49. Methods public String getContentType( ) public int getContentLength( ) public long getDate( ) public long getExpiration( ) public long getLastModified( )
  • 50. Example public class HeaderViewer { public static void main(String args[]) { try { URL u = new URL(&quot;http://www.rediffmail.com/index.html&quot;); URLConnection uc = u.openConnection( ); System.out.println(&quot;Content-type: &quot; + uc.getContentType( )); System.out.println(&quot;Content-encoding: &quot; + uc.getContentEncoding( )); System.out.println(&quot;Date: &quot; + new Date(uc.getDate( ))); System.out.println(&quot;Last modified: &quot; + new Date(uc.getLastModified( ))); System.out.println(&quot;Expiration date: &quot; + new Date(uc.getExpiration( ))); System.out.println(&quot;Content-length: &quot; + uc.getContentLength( )); } // end try catch (MalformedURLException ex) { System.out.println(&quot;I can't understand this URL..&quot;); } catch (IOException ex) { System.err.println(ex); } System.out.println( ); } // end main } // end HeaderViewer
  • 51. Sample Output Sample output: Content-type: text/htmlContent-encoding: nullDate: Mon Oct 18 13:54:52 PDT 1999Last modified: Sat Oct 16 07:54:02 PDT 1999Expiration date: Wed Dec 31 16:00:00 PST 1969 Content-length: -1 Sample output for: http://www.oreilly.com/graphics/space.gif   Content-type: image/gifContent-encoding: nullDate: Mon Oct 18 14:00:07 PDT 1999Last modified: Thu Jan 09 12:05:11 PST 1997Expiration date: Wed Dec 31 16:00:00 PST 1969 Content-length: 57
  • 52. Retrieving Header field public String getHeaderField(String name) Example: String contentType = uc.getHeaderField(&quot;content-type&quot;); String contentEncoding = uc.getHeaderField(&quot;content-encoding&quot;)); String data = uc.getHeaderField(&quot;date&quot;); String expires = uc.getHeaderField(&quot;expires&quot;); String contentLength = uc.getHeaderField(&quot;Content-length&quot;);
  • 53. Datagrams A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed. The java.net package contains three classes to help you write Java programs that use datagrams to send and receive packets over the network: DatagramSocket and DatagramPacket
  • 54. TCP vs. UDP No. TCP UDP 1 This Connection oriented protocol This is connection-less protocol 2 The TCP connection is byte stream The UDP connection is a message stream 3 It does not support multicasting and broadcasting It supports broadcasting 4 It provides error control and flow control The error control and flow control is not provided 5 TCP supports full duplex transmission UDP does not support full duplex transmission 6 It is reliable service of data transmission This is an unreliable service of data transmission 7 The TCP packet is called as segment The UDP packet is called as user datagram.
  • 55. UDP in Java DatagramPacket DatagramSocket
  • 56. Receiving DatagramPacket public DatagramPacket(byte[ ] buffer, int length) public DatagramPacket(byte[ ] buffer, int offset, int length) Example: byte[ ] buffer = new byte[8192]; DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
  • 57. Sending Datagrams public DatagramPacket(byte[ ] data, int length, InetAddress destination, int port) public DatagramPacket(byte[ ] data, int offset, int length, InetAddress destination, int port)
  • 58. DatagramSocket public DatagramSocket( ) throws SocketException public DatagramSocket(int port) throws SocketException public DatagramSocket(int port, InetAddress interface) throws SocketException
  • 59. Sending and Receiving Packets public void send(DatagramPacket dp) throws IOException public void receive(DatagramPacket dp) throws IOException
  • 60. Example : UDPServer UDPClient
  • 61. References 1. Java Network Programming, 3rd Edition, By Elliotte Rusty Harold, O'Reilly, October 2004 Chapter 2: Basic Networking Concepts Chapter 7: URLs and URIs Chapter 9: Sockets for Clients Chapter 10: Sockets for Servers Chapter 13: UDP Datagrams and Sockets Chapter 15: URL Connections 2. Java 2 the Complete Reference , Fifth Edition by Herbert Schildt, 2001, Osborne McGraw Hill. Chapter 18: Networking
  • 62. References 3. Learning Java, 3rd Edition, By Jonathan Knudsen, Patrick Niemeyer, O'Reilly, May 2005 Chapter 13: Network Programming 4. A Laboratory Manual for Java Programming (1526) , by Maharashtra State Board of Technical Education, Mumbai, 2004