Presentation is loading. Please wait.

Presentation is loading. Please wait.

NETWORK PROGRAMMING.

Similar presentations


Presentation on theme: "NETWORK PROGRAMMING."— Presentation transcript:

1 NETWORK PROGRAMMING

2 Introduction The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

3 Introduction The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details.

4 Introduction The java.net package provides support for the two common network protocols: TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.

5 Introduction The java.net package provides support for the two common network protocols: TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.

6 URL Processing Socket Programm

7 Url Processing

8 Url Processing URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory. This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows: protocol://host:port/path?query#ref

9 Url Processing The following is a URL to a Web page whose protocol is HTTP: Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80.

10 URL Class Methods: The java.net.URL class represents a URL and has complete set of methods to manipulate URL in Java. The URL class has several constructors for creating URLs, including the following: (1) public URL(String protocol, String host, int port, String file) throws MalformedURLException. Creates a URL by putting together the given parts.

11 URL Class Methods: (2)public URL(String protocol, String host, String file) throws MalformedURLException Identical to the previous constructor, except that the default port for the given protocol is used. (3) public URL(String url) throws MalformedURLException Creates a URL from the given String

12 URL Class Methods: (4)public URL(URL context, String url) throws MalformedURLException Creates a URL by parsing the together the URL and String arguments

13 URL Class Methods: The URL class contains many methods for accessing the various parts of the URL being represented. Some of the methods in the URL class include the following: (1) public String getPath() --Returns the path of the URL. (2) public String getQuery()--Returns the query part of the URL. (3) public String getAuthority()--Returns the authority of the URL.

14 URL Class Methods: (4)public int getPort() --Returns the port of the URL. (5)public int getDefaultPort() --Returns the default port for the protocol of the URL. (6)public String getProtocol() --Returns the protocol of the URL. (7)public String getHost() --Returns the host of the URL. (8) public String getFile()--Returns the filename of the URL. (9)public String getRef()--Returns the reference part of the URL. (10) public URLConnection openConnection() throws IOException --Opens a connection to the URL, allowing a client to communicate with the resource.

15 Example The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the command line, and the URLDemo program outputs each part of the given URL. See URLDemo in netbeans

16 URLConnections Class Methods
The openConnection() method returns a java.net.URLConnection, an abstract class whose subclasses represent the various types of URL connections. For example: If you connect to a URL whose protocol is HTTP, the openConnection() method returns an HttpURLConnection object. If you connect to a URL that represents a JAR file, the openConnection() method returns a JarURLConnection object. etc...

17 URLConnections Class Methods
The URLConnection class has many methods for setting or determining information about the connection, including the following: (1)Object getContent() --Retrieves the contents of this URL connection. (2)Object getContent(Class[] classes) --Retrieves the contents of this URL connection. (3)String getContentEncoding() --Returns the value of the content- encoding header field. (4)int getContentLength() --Returns the value of the content-length header field.

18 URLConnections Class Methods
(5)String getContentType() --Returns the value of the content-type header field. (6)int getLastModified() --Returns the value of the last-modified header field. (7)long getExpiration() --Returns the value of the expires header field. (8 )long getIfModifiedSince() --Returns the value of this object's ifModifiedSince field.

19 URLConnections Class Methods
(5)String getContentType() --Returns the value of the content-type header field. (6)int getLastModified() --Returns the value of the last-modified header field. (7)long getExpiration() --Returns the value of the expires header field. (8 )long getIfModifiedSince() --Returns the value of this object's ifModifiedSince field. (9)public URL getURL() --Returns the URL that this URLConnection object is connected to

20 Example The following URLConnectionDemo program connects to a URL entered from the command line. If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource is read one line at a time. See URLConnDemo in netbeans

21 Java Socket Programming

22 Socket Programming Socket-The combination of an IP address and a port number. A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and Server Socket--that implement the client side of the connection and the server side of the connection, respectively.

23 Java Sockets Programming
The package java.net provides support for sockets programming (and more). Typically you import everything defined in this package with: import java.net.*;

24 Classes InetAddress Socket ServerSocket DatagramSocket DatagramPacket

25 Server Listening to the port, Establishing connections
Server side program: Listening to the port, Establishing connections Reading from and writing to the socket.

26 Server ServerSocket ssoc=new ServerSocket(1111);
A socket is an end point for communication between two machines Server ServerSocket ssoc=new ServerSocket(1111); This ServerSocket object is used to listen on a port

27 Port is an address that identifies the particular application in destination machine
Port: 1111

28 Client Server Establishing connections Socket csoc=ssoc.accept();
Accepting the connection Client Socket csoc=ssoc.accept(); Client socket object which is bound to same local port(1111) The communication is done through the new socket object

29 In Server program: BufferedReader fromc= new BufferedReader(new InputStreamReader(csoc.getInputStream())) csoc.getInputStream: It reads input from socket object PrintStream toc=new PrintStream(csoc.getOutputStream()); csoc.getOutputStream: It writes stream of data to socket object

30 In client program: PrintStream tos=new PrintStream(soc.getOutputStream()); It writes stream of data to socket object BufferedReader froms=new BufferedReader(new InputStreamReader(soc.getInputStream())); It reads input from socket object BufferedReader fromkb=new BufferedReader(new InputStreamReader(System.in)); Takes the input from keyboard

31

32 TCPClient.java import java.io.*; import java.net.*; class TCPClient {
public static void main(String argv[]) throws Exception {         String sentence;         String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789);         DataOutputStream outToServer =         new DataOutputStream(clientSocket.getOutputStream());

33 TCPClient.java BufferedReader inFromServer =
new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));         sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence);        clientSocket.close();                    } }

34 TCPServer.java import java.io.*; import java.net.*; class TCPServer {
  public static void main(String argv[]) throws Exception     {       String clientSentence;       String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789);   while(true) { Socket connectionSocket = welcomeSocket.accept();            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

35 TCPServer.java DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());            clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence);         }

36 UDP Sockets UDP Socket Programming with UDP
Connectionless and unreliable service. There isn’t an initial handshaking phase. Doesn’t have a pipe. transmitted data may be received out of order, or lost Socket Programming with UDP No need for a welcoming socket. No streams are attached to the sockets. the sending hosts creates “packets” by attaching the IP destination address and port number to each batch of bytes. The receiving process must unravel to received packet to obtain the packet’s information bytes.

37 UDP Sockets DatagramSocket class
DatagramPacket class needed to specify the payload incoming or outgoing

38

39 UDPClient.java import java.io.*; import java.net.*; class UDPClient {
    public static void main(String args[]) throws Exception     {         BufferedReader inFromUser =         new BufferedReader(new InputStreamReader(System.in));         DatagramSocket clientSocket = new DatagramSocket();         InetAddress IPAddress = InetAddress.getByName("hostname");         byte[] sendData = new byte[1024];       byte[] receiveData = new byte[1024];         String sentence = inFromUser.readLine();         sendData = sentence.getBytes();

40 Java Socket Programming
UDPClient.java       DatagramPacket sendPacket =          new DatagramPacket(sendData, sendData.length, IPAddress, 9876);    clientSocket.send(sendPacket);    DatagramPacket receivePacket =          new DatagramPacket(receiveData, receiveData.length);    clientSocket.receive(receivePacket);    String modifiedSentence =          new String(receivePacket.getData());    System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close();       } } Java Socket Programming

41 UDPServer.java import java.io.*; import java.net.*; class UDPServer {
  public static void main(String args[]) throws Exception     {         DatagramSocket serverSocket = new DatagramSocket(9876);         byte[] receiveData = new byte[1024];       byte[] sendData  = new byte[1024];         while(true)         {             DatagramPacket receivePacket =              new DatagramPacket(receiveData, receiveData.length);             serverSocket.receive(receivePacket);             String sentence = new String(receivePacket.getData());

42 UDPServer.java      InetAddress IPAddress = receivePacket.getAddress();      int port = receivePacket.getPort();     String capitalizedSentence = sentence.toUpperCase();         sendData = capitalizedSentence.getBytes();      DatagramPacket sendPacket =        new DatagramPacket(sendData, sendData.length, IPAddress, port);       serverSocket.send(sendPacket);       } }

43 (Email id-jatinit2010@gmail.com/jatin.patel@gperi.ac.in)
CONTACT ME Prof. Jatin Patel ( thank you! 4x3 16x9 Prof. Jatin Patel


Download ppt "NETWORK PROGRAMMING."

Similar presentations


Ads by Google