Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses.

Similar presentations


Presentation on theme: "CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses."— Presentation transcript:

1 CSI 3125, Preliminaries, page 1 Networking

2 CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses are fundamental. The java.net.InetAddress class used to identify an IP address. It is used by most of the other networking classes, including Socket, ServerSocket, URL, DatagramSocket, DatagramPacket. This class represents an Internet address as two fields: hostName (a String) and address (an int). There are no public constructors in the InetAddress class.

3 CSI 3125, Preliminaries, page 3 Inetaddress Class methods HInetAddress has three static methods that return suitably initialized InetAddress objects. static InetAddress getLocalHost( ) throws UnknownHostException- returns the InetAddress of the machine on which it's running. Eg: InetAddress address = InetAddress.getLocalHost(); System.out.println(address);

4 CSI 3125, Preliminaries, page 4 Inetaddress Class methods static InetAddress getByName(String hostName) throws UnknownHostException- returns an InetAddress for a host name passed to it and it throws an UnknownHostException if the host can't be found Eg: address = InetAddress.getByName("amaljyothi.ac.in"); System.out.println(address);

5 CSI 3125, Preliminaries, page 5 Inetaddress Class methods static InetAddress[] getAllByName(String hostName) throw UnknownHostException- Some computers have more than one Internet address. Given a hostname, this method returns an InetAddress array that contains all the addresses corresponding to that name. Eg InetAddress add[] = InetAddress.getAllByName("google.com"); System.out.println(InetAddress.getByName("google.com")); for (int i=0; i<add.length; i++) System.out.println(add[i]);

6 CSI 3125, Preliminaries, page 6 Inetaddress Class prog import java.net.*; class Inet { public static void main(String args[]) throws UnknownHostException { InetAddress address = InetAddress.getLocalHost(); System.out.println(address); address = InetAddress.getByName("amaljyothi.ac.in"); System.out.println(address); InetAddress add[] = InetAddress.getAllByName("google.com"); System.out.println(InetAddress.getByName("google.com")); for (int i=0; i<add.length; i++) System.out.println(add[i]); }

7 CSI 3125, Preliminaries, page 7 TCP & UDP protocols The java.net package provides support two common network protocols: TCP: TCP, Transmission Control Protocol is a connection oriented protocol which allows for reliable communication between two applications. It 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 Example telephone call.

8 CSI 3125, Preliminaries, page 8 TCP & UDP protocols UDP: UDP, User Datagram Protocol, is a connection-less protocol that allows for packets of data to be transmitted between applications. The destination port and IP addresses are written down in a datagram and the datagram is sent to the destination. UDP does not guarantee that packets will be received in the order they were sent

9 CSI 3125, Preliminaries, page 9 TCP & UDP protocols The two computers can communicate until the connection is closed or lost. The java.net.ServerSocket and java.net.Socket classes are need to create a TCP/IP connection between two computers The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.

10 CSI 3125, Preliminaries, page 10 TCP & UDP protocols

11 CSI 3125, Preliminaries, page 11 TCP & UDP protocols Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket.

12 CSI 3125, Preliminaries, page 12 TCP & UDP protocols The reading and writing of data over the socket is accomplished via the familiar stream classes. Each socket has both an OutputStream and an InputStream. The client’s OutputStream is connected to the server’s InputStream, and the client’s InputStream is connected to the server’s OutputStream. TCP is a two way communication protocol, so data can be sent across both streams at the same time.

13 CSI 3125, Preliminaries, page 13 Socket Class The java.net.Socket class is Java's fundamental class for performing client-side TCP operations. It contains constructor that is used to create stream socket that connects to specific port number associated with exactly one host. Following are two most commonly used constructors of Socket class. Socket(String hostName, int port) Creates a socket that connects to the given port number on the specified host. If the domain name server cannot resolve the hostname or is not functioning, the constructor throws an UnknownHostException. If the socket cannot be opened for some other reason, the constructor throws an IOException

14 CSI 3125, Preliminaries, page 14 Socket Class Socket(InetAddress ipAddress, int port) Creates a socket that connects to the given port number at the specified IP address. It uses an InetAddress object to specify the host rather than a hostname. It throws an IOException if it can't connect

15 CSI 3125, Preliminaries, page 15 Socket Class Methods InetAddress getInetAddress()- tells which remote host the Socket is connected to int getPort() - tells you which port the Socket is connected to on the remote host. InputStream getInputStream()-returns an input stream that can read data from the socket into a program. It can be chained with BufferedInputStream or a BufferedReader

16 CSI 3125, Preliminaries, page 16 Socket Class Methods OutputStream getOutputStream()-returns a raw OutputStream for writing data from application to the other end of the socket. It can be chained with DataOutputStream or OutputStreamWriter public void close()- Closes the socket,

17 CSI 3125, Preliminaries, page 17 Implementing A Client 1. Creates a new socket with a Socket() constructor 2. The socket attempts to connect to the remote host. 3. Once the connection is established, the local and remote hosts get input and output streams from the socket. 4. When the transmission of data is complete, one or both sides close the connection.

18 CSI 3125, Preliminaries, page 18 SERVERSOCKET Class To establish a server, create a server socket and attach it to a port, which is where the server listens for connections. The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests. constructors of this class public ServerSocket (int port)- creates a server socket on the port specified by the argument. The constructor throws an IOException

19 CSI 3125, Preliminaries, page 19 SERVERSOCKET Class method public int getLocalPort()-Returns the port that the server socket is listening on public Socket accept() - returns a Socket object representing the connection between the remote client and the local server

20 CSI 3125, Preliminaries, page 20 Implementing A Server 1. A new ServerSocket is created on a particular port using a ServerSocket() constructor. 2. The server invokes the accept() method of the ServerSocket class. accept() blocks until a client attempts to make a connection, at which point accept() returns a Socket object connecting the client and the server. 3. Depending on the requirement, either getInputStream() method, getOutputStream() method, or both are called to get input and output streams that communicate with the client. 4. The server and the client interact each other. 5. The server, the client, or both close the connection. 6. The server returns to step 2 and waits for the next connection.

21 CSI 3125, Preliminaries, page 21 Client Server interaction

22 CSI 3125, Preliminaries, page 22 Client Prog import java.io.*; import java.net.*; class Client { public static void main(String args[]) throws IOException, UnknownHostException { Socket s=new Socket("localhost",5555); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String line; System.out.println("Enter characters"); do { line=br.readLine(); PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true); pw.println(line); } while(!line.equals("EXIT")); s.close(); }

23 CSI 3125, Preliminaries, page 23 Server Prog import java.net.*; import java.io.*; class Server { ServerSocket ss; Socket s; BufferedReader br; String str; public Server() { try { ss=new ServerSocket(5555); s=ss.accept(); br=new BufferedReader(new InputStreamReader(s.getInputStream())); System.out.println("CONNECTED"); do { str=br.readLine(); System.out.println(str); } while(!str.equals("EXIT")); ss.close(); } catch(Exception e) { } public static void main(String args[]) { Server s = new Server(); }

24 CSI 3125, Preliminaries, page 24 User Datagram Protocol User Datagram Protocol (UDP) provides a protocol for sending packets of data called datagrams between applications. If TCP is similar to placing a telephone call, UDP can be compared to mailing someone a letter. The datagram packet is like a letter, where a client sends a datagram to a server without actually connecting to the server. This makes UDP an unreliable communication protocol when compared to TCP, where the client and server are directly connected.

25 CSI 3125, Preliminaries, page 25 User Datagram Protocol If I mail you two letters on the same day, they might be delivered on the same day. In fact, there is no guarantee that both letters will even get delivered at all. The same is true for datagram packets. UDP does not guarantee that packets will be received in the order they were sent. Datagram packets are used to implement a connectionless packet delivery protocol. Each packet needs to have destination address and each packet might be routed differently, and might arrive in any order.

26 CSI 3125, Preliminaries, page 26 User Datagram Protocol The java.net.DatagramPacket and java.net.DatagramSocket classes are used to send and receive datagram packets. The DatagramPacket class stuffs bytes of data into UDP packets called datagrams and lets you unstuff datagrams that you receive. A DatagramSocket sends as well as receives UDP datagrams. To send data, you put the data in a DatagramPacket and send the packet using a DatagramSocket. To receive data, you receive a DatagramPacket object from a DatagramSocket and then read the contents of the packet. In UDP, everything about a datagram, including the address to which it is directed, is included in the packet itself; the socket needs to know only the local port on which to listen or send.

27 CSI 3125, Preliminaries, page 27 User Datagram Protocol All the data you stuff into a single datagram is sent as a single packet and is either received or lost as a group. One packet is not necessarily related to the next. Given two packets, there is no way to determine which packet was sent first and which was sent second

28 CSI 3125, Preliminaries, page 28 Datagramsocket Class The java.net.DatagramSocket class is used by both the sender and the recipient of a datagram packet to send and receive a packet, respectively. constructors for DatagramSocket: DatagramSocket(int port) throws SocketException-Creates a datagram socket on the localhost computer at the specified port. DatagramSocket(int port, InetAddress address) throws SocketException)- Creates a datagram socket using the specified port and local address.

29 CSI 3125, Preliminaries, page 29 Datagramsocket Class METHODS public void send(DatagramPacket packet) throws IOException- Sends the specified datagram packet. The DatagramPacket object contains the destination information of the packet. public void receive(DatagramPacket packet) throws IOException- This method receives a single UDP datagram from the network and stores it in the pre-existing DatagramPacket object.

30 CSI 3125, Preliminaries, page 30 Datagrampacket Class In Java, a UDP datagram is represented by an instance of the DatagramPacket. This class provides methods to get and set the source or destination address from the IP header, to get and set the source or destination port, to get and set the data, and to get and set the length of the data. There are two types of constructors for DatagramPacket. The first constructor is used to receive data from the net; The second is for data that you will send to the net.

31 CSI 3125, Preliminaries, page 31 Datagrampacket Class public DatagramPacket(byte[] buffer, int length)- Creates a datagram packet for receiving a packet of the specified size. The buffer will contain the incoming packet. The array of bytes passed in to these constructors is used to contain the data of the incoming packet, and typically are empty arrays

32 CSI 3125, Preliminaries, page 32 Datagrampacket Class public DatagramPacket(byte[] buffer, int length, InetAddress address, int port)- Creates a datagram packet for sending a packet of the specified size. The buffer contains the data of the packet, and the address and port denote the recipient.

33 CSI 3125, Preliminaries, page 33 Datagrampacket Class METHODS DatagramPacket has five methods InetAddress getAddress()-The getAddress() method returns an InetAddress object containing the address of the remote host. int getPort( ) -The getPort() method returns an integer specifying the remote port.

34 CSI 3125, Preliminaries, page 34 Receiving A Datagram Packet 1. Create an array of bytes large enough to hold the data of the incoming packet. 2. Create object of DatagramPacket using the array of bytes. 3. A DatagramSocket is instantiated, and it is specified which port. 4. The receive() method of the DatagramSocket class is invoked, passing in the DatagramPacket object. This blocks the execution of further code until a datagram packet is received or a time out occurs

35 CSI 3125, Preliminaries, page 35 Sending A Datagram Packet 1. Create an array of bytes large enough to hold the data of the packet to be sent, and fill the array with the data. 2. Create a new DatagramPacket object that contains the array of bytes, as well as the server name and port number of the recipient. 3. A DatagramSocket is instantiated, and it is specified which port on the localhost the socket will bind to. 4. The send() method of the DatagramSocket class is invoked, passing in the DatagramPacket object.

36 CSI 3125, Preliminaries, page 36 UDP Client 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("localhost"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); 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("Ffrom server:" + modifiedSentence); clientSocket.close(); }

37 CSI 3125, Preliminaries, page 37 UDP Server 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()); 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); }

38 CSI 3125, Preliminaries, page 38 URL CLASS URL stands for Uniform Resource Locator, represents a resource on the World Wide Web, such as a Web page or FTP directory. The java.net.URL class represents a URL. Constructor URL(String url)- Creates a URL from the given String. Eg URL url = new URL("https://poposir.orgfree.com");

39 CSI 3125, Preliminaries, page 39 URL CLASS methods public String getPath()-Returns the path of the URL. public String getQuery()-Returns the query part of the URL. public String getAuthority()-Returns the authority of the URL. public int getPort()-Returns the port of the URL. public int getDefaultPort()-Returns the default port for the protocol ofthe URL. public String getProtocol()-Returns the protocol of the URL. public String getHost()-Returns the host of the URL. public String getFile()-Returns the filename of the URL. public String getRef()-Returns the reference part of the URL.

40 CSI 3125, Preliminaries, page 40 URL CLASS prog import java.net.*; import java.io.*; public class URLDemo { public static void main(String [] args) throws Exception { URL url = new URL("https://poposir.orgfree.com/index.php?user=popo#inbox"); System.out.println("URL is " + url.toString()); System.out.println("protocol is " + url.getProtocol()); System.out.println("authority is " + url.getAuthority()); System.out.println("file name is " + url.getFile()); System.out.println("host is " + url.getHost()); System.out.println("path is " + url.getPath()); System.out.println("port is " + url.getPort()); System.out.println("default port is " + url.getDefaultPort()); System.out.println("query is " + url.getQuery()); System.out.println("ref is " + url.getRef()); }

41 CSI 3125, Preliminaries, page 41 URL CLASS


Download ppt "CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses."

Similar presentations


Ads by Google