Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topic: Network programming

Similar presentations


Presentation on theme: "Topic: Network programming"— Presentation transcript:

1 Topic: Network programming
& Java Sockets Course : JAVA PROGRAMMING Paper Code: ETCS-307 Faculty : Dr. Prabhjot Kaur Associate Professor, Dept. of Information Technology 1

2 Hosts Devices connected to the Internet are called hosts
Most hosts are computers, but hosts also include routers, printers, fax machines, PDAs, Tablets, etc.

3 Internet addresses Every host on the Internet is identified by a unique, four-byte Internet Protocol (IP) address. This is written in dotted quad format like where each byte is an unsigned integer between 0 and 255. There are about four billion unique IP addresses, but they aren’t very efficiently allocated

4 Domain Name System (DNS)
Numeric addresses are mapped to names like " or "star.blackstar.com" by DNS. Each site runs domain name server software that translates names to IP addresses and vice versa DNS is a distributed system

5 The InetAddress Class The java.net.InetAddress class represents an IP address. It converts numeric addresses to host names and host names to numeric addresses. It is used by other network classes like Socket and ServerSocket to identify hosts

6 IP Addresses and Java Java has a class java.net.InetAddress which abstracts network addresses Serves three main purposes: Encapsulates an address and domain name Performs name lookup (converting a host name into an IP address) Performs reverse lookup (converting the address into a host name)

7 java.net.InetAddress Static construction using a factory method
InetAddress getByName(String hostName) hostName can be “host.domain.com.au”, or hostName can be “ ” InetAddress getLocalHost() Some useful methods: String getHostName() Gives you the host name (for example “ String getHostAddress() Gives you the address (for example “ ”) InetAddress[] getAllByName(String hostName) Factory methods: a convention whereby static methods in a class return an instance of a class.

8 Creating InetAddresses
There are no public InetAddress() constructors. Arbitrary addresses may not be created. All addresses that are created must be checked with DNS

9 Getter Methods public boolean isMulticastAddress()
public String getHostName() public byte[] getAddress() public String getHostAddress()

10 Utility Methods public int hashCode() public boolean equals(Object o)
public String toString()

11 Ports In general a host has only one Internet address
This address is subdivided into 65,536 ports Ports are logical abstractions that allow one host to communicate simultaneously with many other hosts Many services run on well-known ports. For example, http tends to run on port 80

12 URLs A URL, short for "Uniform Resource Locator", is a way to unambiguously identify the location of a resource on the Internet.

13 Example URLs http://java.sun.com/
file:///Macintosh%20HD/Java/Docs/JDK% %20docs/api/java.net.InetAddress.html#_top_ ftp://ftp.info.apple.com/pub/ telnet://utopia.poly.edu

14 The Pieces of a URL the protocol, aka scheme the authority
user info user name password host name or address port the path, aka file the ref, aka section or anchor the query string Most URLs can be broken into about five pieces, not all of which are necessarily present in any given URL. These are: There may also be a query string part which is used for CGI data. We’ll talk about that when we discuss CGIs.

15 The java.net.URL class A URL object represents a URL.
The URL class contains methods to create new URLs parse the different parts of a URL get an input stream from a URL so you can read data from a server get content from the server as a Java object

16 Example try { URL u = new URL(" "); System.out.println("The protocol is " + u.getProtocol()); System.out.println("The host is " + u.getHost()); System.out.println("The port is " + u.getPort()); System.out.println("The file is " + u.getFile()); System.out.println("The anchor is " + u.getRef()); } catch (MalformedURLException e) { }

17 Elements of C-S Computing
a client, a server, and network Request Client Server Network Result Client machine Server machine

18 Networking Basics Applications Layer Transport Layer Network Layer
Standard apps HTTP FTP Telnet User apps Transport Layer TCP UDP Programming Interface: Sockets Network Layer IP Link Layer Device drivers TCP/IP Stack Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)

19 Networking Basics TCP (Transport Control Protocol) is a connection-oriented protocol that provides a reliable flow of data between two computers. Example applications: HTTP FTP Telnet TCP/IP Stack Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)

20 Networking Basics UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. Example applications: Clock server Ping TCP/IP Stack Application (http,ftp,telnet,…) Transport (TCP, UDP,..) Network (IP,..) Link (device driver,..)

21 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 TCP Client app app app app port port port port TCP or UDP Packet Data port# data

22 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

23 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.

24 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 Connection request port Client

25 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 port port Client port Connection

26 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

27 Client/server socket interaction: TCP
Server (running on hostid) Client create socket, port=x, for incoming request: welcomeSocket = ServerSocket() TCP connection setup close connectionSocket read reply from clientSocket create socket, connect to hostid, port=x clientSocket = Socket() wait for incoming connection request connectionSocket = welcomeSocket.accept() send request using clientSocket read request from connectionSocket write reply to

28 JAVA TCP Sockets In Package java.net java.net.Socket
Implements client sockets (also called just “sockets”). An endpoint for communication between two machines. Constructor and Methods Socket(String host, int port): Creates a stream socket and connects it to the specified port number on the named host. InputStream getInputStream() OutputStream getOutputStream() close() java.net.ServerSocket Implements server sockets. Waits for requests to come in over the network. Performs some operation based on the request. ServerSocket(int port) Socket Accept(): Listens for a connection to be made to this socket and accepts it. This method blocks until a connection is made.

29 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());

30 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();                    } }

31 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()));

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

33 Socket Exceptions try {
Socket client = new Socket(host, port); handleConnection(client); } catch(UnknownHostException uhe) { System.out.println("Unknown host: " + host); uhe.printStackTrace(); catch(IOException ioe) { System.out.println("IOException: " + ioe); ioe.printStackTrace();

34 Client/server socket interaction: UDP
Server (running on hostid) create socket, clientSocket = DatagramSocket() Client Create, address (hostid, port=x, send datagram request using clientSocket create socket, port=x, for incoming request: serverSocket = DatagramSocket() read request from serverSocket close clientSocket read reply from clientSocket write reply to serverSocket specifying client host address, port umber

35 JAVA UDP Sockets In Package java.net java.net.DatagramSocket
A socket for sending and receiving datagram packets. Constructor and Methods DatagramSocket(int port): Constructs a datagram socket and binds it to the specified port on the local host machine. void receive( DatagramPacket p) void send( DatagramPacket p) void close()

36 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();

37 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();       } }

38 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());

39 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);       } }

40 Thank You


Download ppt "Topic: Network programming"

Similar presentations


Ads by Google