You are on page 1of 53

Unit-2 Networking

By: Neha Aggarwal (Senior Lecturer CSE/IT)

Client Server Communication


a client, a server, and network

Client Server Network

Client machine Server machine


2

For Writing a Network Program U Need :

Communication protocols : TCP & UDP Ports & Internet Addresses. Sockets URL (Uniform Resource Locator) Streams. Classes in java.io and java.net packages.
3

TCP (Transmission Control Protocol)

Provides the ability to acknowledge receipt of IP packets & request of retransmission of lost packets. Allows the received packets to be put back together in the order they were sent. Supported classes in java.net : URL, URLConnection, Socket & ServerSocket.

UDP (User Datagram Protocol)

Is also an alternative protocol for sending data . Is an unreliable protocol that does not guarantee that packets will arrive at their destination. Does not guarantee that packets are delivered in the correct order. Classes supported in java.net : DatagramPacket, DatagramSocket. DatagramPacket class stuffs bytes of data into UDP packets calles datagrams. DatagramSocket sends as well as receive UDP datagrams.
5

Ports

Each port from the server can be treated by clients as a separate machine offering different services.
app app

server

P o r t

TCP

Client

app

app

port

port

port

port Packet Data

TCP or UDP

port# data
6

Ports

Port numbers are represented by 16-bit numbers(0 to 65,535).

Port numbers ranging from 0 to 1023 are reserved for well known services like : SMTP 25 FTP 21
7

Internet Addressing

IP address is a unique number for identifying a device like 137.92.11.13 The host name & IP address is represented by java.net.InetAddress Its methods include: InetAddress getByName(String host) String getHostName();
8

Socket

If u are a client ,u need an API that will allow u to send messages to that service & read replies from it. if u are a server, u need to be able to create a port & listen at it. u need to be able to read the messages that comes in & reply to it. The Socket & ServerSocket are client & server classes to do this.
9

Socket Communication

A server 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
Client

port

10

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 so that it can continue to listen to the original socket for connection requests while serving the connected client.

port port Connection


11

server port

Client

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. Javas .net package provides two classes:

Socket for implementing a client ServerSocket for implementing a server


12

Implementing a Client
1. Create a Socket Object: Socket client = new Socket(hostname, portnumber);

2. Create Output stream that can be used to send information to the server.
PrintWriter out = new PrintWriter (client.getOutputStream());

13

Implementing a Client
3. Create Input Stream to read the response from server BufferedReader in = new BufferedReader(new InputStreamReader(client.getIn putStream()));

4. Close the socket when done: client.close();


14

Implementing a Server
1. Create a ServerSocket object . ServerSocket listenSocket= new ServerSocket(portNumber); 2. Create Socket object from ServerSocket Socket server=listenSocket.accept(); 3. Create Input Stream to read client Input BufferedReader in = new BufferedReader(new InputStreamReader (server.getInputStream()));
15

Implementing a Server
4. Create Output streamused to send info back to client PrintWriter out = new PrintWriter (server.getOutputStream))); 5. Close the Socket Server.close();

16

Client Server Program


import java.io.*; import java.net.*; public class cli { public static void main(String s[] ) { try { Socket server; String str=""; DataInputStream d=new DataInputStream(System.in); PrintStream toserver; BufferedReader fromserver; server=new Socket("192.168.0.66",1096); InputStreamReader isr=new InputStreamReader(server.getInputStream());
17

Client Server Program


fromserver= new BufferedReader(isr); toserver=new PrintStream(server.getOutputStream()); while(true) { str=":"+d.readLine(); toserver.println(str); str=fromserver.readLine(); System.out.println(str); } } catch(Exception e) { System.out.println(e); } } }
18

Client Server Program


Serve.java import java.io.*; import java.net.*; public class serve { public static void main(String s[]) { ServerSocket sc; Socket client; DataInputStream d; PrintStream toClient; BufferedReader fromClient; String str=""; try { d=new DataInputStream(System.in);
19

Client Server Program

sc=new ServerSocket(1096); System.out.println("ServerStarted"); client=sc.accept(); InputStreamReader isr=new InputStreamReader(client.getInputStream()); fromClient=new BufferedReader(isr); toClient=new PrintStream(client.getOutputStream()); while(true) { str=fromClient.readLine(); System.out.println(str); str=":"+d.readLine(); toClient.println(str); } } catch(Exception e) { System.out.println(e); } } }
20

URL

URL is Uniform Resource Locator. It is a reference (an address) to a resource on the web server. java.net package uses a class called URL to represent a URL address. A URL takes the form of a string that describes how to find a resource on the web server. It consists of two main components: protocol needed to access the resource and the location of the resource.
21

URL

The protocol identifier indicates the name of the protocol to be used to fetch the resource. The resource name is the complete address to the resource.

The resource name contains components : 1) Host Name: The name of the machine on which the resource lives.
22

URL
2) Filename : The pathname to the file on the machine. 3) Port Number :The port number to which to connect .

4) Reference : identifies a specific location within a file .


23

Creating a URL
Absolute URL -An absolute URL contains all
of the information necessary to reach the resource. URL u = new URL ("http://www.gmail.com/"); This URL object called an absolute URL. Relative URL A relative URL contains only enough information to reach the resource relative to another URL. Eg: suppose u know two URLs at the Gmail site.
24

RELATIVE URL

http://www.gmail.com/pages/Gmail.login.html http://www.gmail.com/pages/Gmail.first.html U can create URL objects for these pages relative to their common base URL: http://www.gmail.com/pages/ like this: URL gmail = new URL("http://www.gmail.com/pages/"); URL gmailLogin = new URL(gmail, "Gmail.login.html"); URL gmailFirst = new URL(gmail, "Gmail.first.html");
25

Constructors
1) URL(String s) Creates a URL object from the String representation. 2) URL(String protocol, String host, int port, String file) Creates a URL object from the specified protocol, host, port number, and file. 3) URL(String protocol, String host, String file) Creates a URL from the specified protocol name, host name, and file name.
26

Methods
1) getContent() Gets the contents of this URL 2) getFile() Gets the file name of this URL. 3) getHost() Gets the host name of this URL 4) getPort() Gets the port number of this URL.
27

Methods
5)

6)

7)

getProtocol() Gets the protocol name of this URL. openConnection() represents a connection to the remote object referred by URL. openStream() returns an InputStream for reading from that connection.
28

URL CONNECTION

1)

2)

Once you have successfully created an instance of the URL class, you can begin to call operations on it. open a connection, so that u can access the resource represented by the URL. On successfully connected, it returns an instance of the URLConnection class.

29

Opening a Connection
try { URL url = new URL("http://www.yahoo.com"); URLConnection connection = url.openConnection(); } catch (MalformedURLException e) { System.out.println(e); } }

30

Reading From a URL

Once you have a successful connection,u can retrieve the input stream for the connection and begin reading. java.io classes operate on data returned from URLConnection streams. openStream() method get a stream from which you can read the contents of the URL. The openStream() method returns a java.io.InputStream object
31

Eg: Reading From a URL


import java.net.*; import java.io.*; public class URLReader { public static void main(String args[]) try { URL url = new URL("http://www.yahoo.com"); URLConnection connection = url.openConnection(); connection.setDoInput(true);
32

Eg: Reading From a URL


InputStream in = connection.getInputStream(); BufferedReader b = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = b.readLine()) != null) System.out.println(line); b.close(); } catch (Exception e) { System.out.println(e); } }
33

Writing to a URL

successful connection, you can retrieve the output stream for the connection and begin writing. Many HTML pages contain forms-- text fields and other GUI objects that let you enter data to send to the server. After you type in the required information and initiate the query by clicking a button, your Web browser writes the data to the URL over the network .

34

Writing to a URL

At the other end the server receives the data, processes it, and then sends you a response. HTTP use POST method to send data to the server. The server recognizes the POST request and reads the data sent from the client. Before retrieving and writing to a URLConnection stream, you need to designate the connection as being write-enabled by setting the Output property to true using the setDoOutput() method .

35

Eg: Writing to a URL


import java.net.*; import java.io.*; public static void main(String args[]) { try { URL url = new URL("http://www.yahoo.com"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStream outStream = connection.getOutputStream();
36

Eg: Writing to a URL


ObjectOutputStream objectStream = new ObjectOutputStream(outStream); objectStream.writeInt(54367); objectStream.writeObject("Hello there"); } catch (Exception e) { System.out.println(e); } }
37

Advanced Socket Programming


Socket Timeouts Internet Addresses Interruptible sockets Half Close

38

Socket Timeouts

We use socket timeouts to deal with connection errors. If the host machine is unreachable then our application waits for a long time & your operating system times out u eventually. So to avoid this, u should decide what timeout value is reasonable for your application. Call the setSoTimeout() method to set a timeout value (in milliseconds).
39

Socket Timeouts

Socket s=new Socket (host name, port number);

s.setSoTimeout(10000);
It will throw SocketTimeoutException, when the timeout has been reached before the operation has completed its work.
40

Internet Addresses

Each computer is identified by a unique number called an Internet address or an IP address. IP addresses are four bytes long, these are referred to as IPv4 addresses. Bytes are separated by periods.For example,address for www.yahoo.com is 152.2.21.2.
41

InetAddress Class

U can use this class, if u need to convert between host names & Internet addresses. getByName() method returns an InetAddress object of a host. InetAddress address=InetAddress.getByName(www.yah oo.com); this returns an IP address of this host name.
42

Interruptible Sockets

When u connect to a socket, current thread


blocks until the connection has been established or timeout has elapsed. If u want to give users an option to cancel a socket connection that doesnot producing a result, u will call interrupt. To interrupt a socket operation, u will use a SocketChannel, a feature of java.nio package.
43

Interruptible Sockets
1) Open the SocketChannel like this : SocketChannel channel = SocketChannel.open(new InetSocketAddress(host, port)); SocketChannel has read & write methods that are declared in interfaces ReadableByteChannel & WriteableByteChannel. We will use Scanner class to read a SocketChannel .Scanner has a constructor with a ReadableByteChannel parameter.
44

Interruptible Sockets
2) Scanner in =new Scanner(channel); 3) To turn a channel into an output stream ,use Channel.newOutputStream method. OutputStream out= Channels.newOutputStream(channel); Now whenever a thread is interrupted during an open, read & write, the operation doesnot block but is terminated with an exception.
45

Half Close

When a client program sends a request to a server, the server needs to be able to determine when the end of the request occurs (ends of writing of data to server). Indicating the end of the request data is harder than writing data to a file. If u close a socket, then u immediately disconnect from a server. The Half Close overcomes this problem, by closing the output stream of a socket, indicating to the server the end of request data.
46

Half Close

Socket s = new Socket (host name, port number); Scanner in = new Scanner (socket.getInputStream()); PrintWriter writer= new PrintWriter(socket.getOutputStream()); writer.print(end of data); socket.shutdownOutput();
47

Sending Email
What is SMTP ? Simple Mail Transport Protocol (SMTP) is the network protocol used to send email across the Internet.

SMTP is generally used to send messages from a mail client to a mail server.

48

Steps for Sending Email


1) Importing the necessary packages: import com.jscape.inet.smtp.*; Import com.jscape.inet.email.*; The com.jscape.inet.smtp package contains the necessary classes for communicating with an SMTP server. The com.jscape.inet.email package contains the necessary classes for generating an email message.
49

Steps for Sending Email


2) Establishing a Connection : To send email you must first establish a network connection to your SMTP server. create a new Smtp instance using SMTP hostname as argument. Smtp smtp = new Smtp("smtp.yahoo.com");

establish connection smtp.connect();


50

Steps for Sending Email


3) Composing the Email : Create a new EmailMessage instance EmailMessage message = new EmailMessage(); set From address message.setFrom(abc@yahoo.com"); set To address message.setTo(xyz@yahoo.com");
51

Steps for Sending Email


set subject of message message.setSubject("Hello!"); set body of message message.setBody("Have a nice day"); set carbon-copy recipients message.setCc(one@yahoo.com");

52

Steps for Sending Email


4) Sending the Email : send the email message smtp.send(message); 5) Releasing the Connection : release SMTP server connection smtp.disconnect();

53

You might also like