[go: up one dir, main page]

0% found this document useful (0 votes)
34 views47 pages

Unit 1

The document discusses Java networking concepts including: 1. Network basics and socket overview including client-server communication using sockets 2. The InetAddress class which represents IP addresses and methods like getByName() 3. TCP/IP server sockets using ServerSocket to establish communication between a server and clients 4. TCP/IP client sockets using Socket to implement client sockets 5. Additional topics on datagrams, URLs, and URL connections.

Uploaded by

Only Login
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views47 pages

Unit 1

The document discusses Java networking concepts including: 1. Network basics and socket overview including client-server communication using sockets 2. The InetAddress class which represents IP addresses and methods like getByName() 3. TCP/IP server sockets using ServerSocket to establish communication between a server and clients 4. TCP/IP client sockets using Socket to implement client sockets 5. Additional topics on datagrams, URLs, and URL connections.

Uploaded by

Only Login
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Advance java Programming

Unit-1
Java Networking
Unit-1: Java Networking
Topic
1. Network Basics and Socket overview
2. InetAddress
3. TCP/IP server sockets
4. TCP/IP client sockets
5. Datagrams
6. URL
7. URLConnection

Unit-1 JAVA NETWORKING 2 Darshan Institute of Engineering & Technology


Network Basics: java.net pacakage
 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.
Java.net Package

InetAddress This class represents an


import java.net.* Class represents
Internet Protocol a address.
(IP) Uniform
URL Resource Locator, a pointer to a
URLConnection "resource"
Representon the
the communications
World Wide link
ServerSocket Web.
Used to create
between a server and
the application socket.
a URL
TCP This object is used to establish
Socket communication with theclient
This class implements clients.
sockets.
DatagramPacket This class represents a
UDP DatagramSocket datagram packet.
Represents a socket for sending
and receiving datagram
packets.

Unit-1 JAVA NETWORKING 3 Darshan Institute of Engineering & Technology


Socket overview
Socket
 “A socket is one endpoint of a two-way communication link
between two programs running on the network.”
 A Socket is combination of an IP address and a port number.

Unit-1 JAVA NETWORKING 4 Darshan Institute of Engineering & Technology


Client – Server Communication
 Two machines must connect
 Server waits for connection
 Client initiates connection
 Server responds to the client request

Server Client
Response
socket socket
Request
Waits

Unit-1 JAVA NETWORKING 5 Darshan Institute of Engineering & Technology


Socket overview
• The server is just like any ordinary program running in a computer.
• Each computer is equipped with some ports.

Unit-1 JAVA NETWORKING 6 Darshan Institute of Engineering & Technology


Socket overview
• The server connects to one of the ports.
• This process is called binding to a port.
• The connection is called a server socket.

The Java server code that does this is:


ServerSocket ss = new ServerSocket(1234);//1234 is port number

Reference: isinotes/javatut/net

Unit-1 JAVA NETWORKING 7 Darshan Institute of Engineering & Technology


Socket overview
• Server is waiting for client machine to connect.

Reference: isinotes/javatut/net

Unit-1 JAVA NETWORKING 8 Darshan Institute of Engineering & Technology


Socket overview

Reference: isinotes/javatut/net

Unit-1 JAVA NETWORKING 9 Darshan Institute of Engineering & Technology


Socket overview
• In the next step the client connects to this port of the server's computer.
• The connection is called a (client) socket.

Socket sock = new Socket("www.gtu.ac.in",80);


/* The client knows the number 80 */

Reference: isinotes/javatut/net

Unit-1 JAVA NETWORKING 10 Darshan Institute of Engineering & Technology


Socket overview
• Now, connection is established between client and server.

Reference: isinotes/javatut/net

Unit-1 JAVA NETWORKING 11 Darshan Institute of Engineering & Technology


Socket overview

Reference: isinotes/javatut/net

Unit-1 JAVA NETWORKING 12 Darshan Institute of Engineering & Technology


Socket overview
Everytime a client is found, its Socket is extracted, and the loop again waits for the
next client.

Reference: isinotes/javatut/net

Unit-1 JAVA NETWORKING 13 Darshan Institute of Engineering & Technology


Socket overview
Client 2

Server

Client 1

Reference: isinotes/javatut/net

Unit-1 JAVA NETWORKING 14 Darshan Institute of Engineering & Technology


Unit-1: Java Networking
Topic
1. Network Basics and Socket overview
2. InetAddress
3. TCP/IP server sockets
4. TCP/IP client sockets
5. Datagrams
6. URL
7. URLConnection

Unit-1 JAVA NETWORKING 15 Darshan Institute of Engineering & Technology


InetAddress
java.net package
• This class represents an Internet Protocol (IP) address.
• The java.net.InetAddress class provides methods to get an IP of host name.

Example
InetAddress ip
=InetAddress.getByName("www.gtu.ac.in");
System.out.println(“ip:“+ ip);

Output:
ip: www.gtu.ac.in/89.238.188.50

Unit-1 JAVA NETWORKING 16 Darshan Institute of Engineering & Technology


InetAddress : Method
Method Description
public static InetAddress Determines the IP address of a given host's
getByName(String host) name.
throws UnknownHostException

Example

InetAddress ip
=InetAddress.getByName("www.gtu.ac.in");
System.out.println(“ip:“+ ip);

Output:
ip: www.gtu.ac.in/89.238.188.50

Unit-1 JAVA NETWORKING 17 Darshan Institute of Engineering & Technology


InetAddress : Method
Method Description
public static InetAddress Returns the address of the local host.
getLocalHost()
throws UnknownHostException

Example

InetAddress ip=InetAddress.getLocalHost();
System.out.println(“LocalHost:“+ip);

Output:
LocalHost:My-PC/10.254.3.34

Unit-1 JAVA NETWORKING 18 Darshan Institute of Engineering & Technology


InetAddress : Method
Method Description
public String getHostName() it returns the host name of the IP address.

Example

InetAddress ip=InetAddress.getByName("10.254.3.34");
System.out.println(“Hostname:”+ip.getHostName());

Output:
Hostname:My-PC

Unit-1 JAVA NETWORKING 19 Darshan Institute of Engineering & Technology


InetAddress : Method
Method Description
public String getHostAddress() it returns the IP address in string format.

Example
InetAddress ip=InetAddress.getByName("www.gtu.ac.in");
System.out.println(“HostAddress:”+ip.getHostAddress());

Output:
HostAddress:89.238.188.50

Unit-1 JAVA NETWORKING 20 Darshan Institute of Engineering & Technology


InetAddress: Program
import java.net.*; //required for InetAddress Class
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip
=InetAddress.getByName("www.gtu.ac.in");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address:"+ip.getHostAddress());
}
catch(Exception e){System.out.println(e);}
}
}

Output:
Host Name: www.gtu.ac.in
IP Address: 89.238.188.50

Unit-1 JAVA NETWORKING 21 Darshan Institute of Engineering & Technology


InetAddress: Method Summary
static InetAddress Determines the IP address of a given host's name.
getByName(String host)

static InetAddress Returns the address of the local host.


getLocalHost()

public String getHostName() it returns the host name of the IP address.

public String getHostAddress() it returns the IP address in string format.

String toString() Converts this IP address to a String.

boolean equals(Object obj) Compares this object against the specified object.

static InetAddress[] Returns an array of its IP addresses, based on the


getAllByName(String host) configured name service on the system.

static InetAddress Returns the loopback address.


getLoopbackAddress()

Unit-1 JAVA NETWORKING 22 Darshan Institute of Engineering & Technology


Unit-1: Java Networking
Topic
1. Network Basics and Socket overview
2. InetAddress
3. TCP/IP server sockets
4. TCP/IP client sockets
5. Datagrams
6. URL
7. URLConnection

Unit-1 JAVA NETWORKING 23 Darshan Institute of Engineering & Technology


TCP/IP Client-Server sockets
Java.net

InetAddress
URL
URLConnection This class implements Server sockets
ServerSocket
TCP
Socket This class implements Client sockets.
DatagramPacket
DatagramSocket
MulticastSocket

Unit-1 JAVA NETWORKING 24 Darshan Institute of Engineering & Technology


TCP/IP ServerSocket Class
 The ServerSocket class (java.net) can be used to create a server
socket.
 This object is used to establish communication with the clients.

Constructor
ServerSocket(int port) Creates a server socket, bound to the specified
port.

Method
public Socket accept() returns the socket and establish a connection
between server and client.

Unit-1 JAVA NETWORKING 25 Darshan Institute of Engineering & Technology


TCP/IP Server Sockets
Syntax
ServerSocket ss;
ss=new ServerSocket(Port_no);

Example
ServerSocket ss=new ServerSocket(1111);

Unit-1 JAVA NETWORKING 26 Darshan Institute of Engineering & Technology


TCP/IP Server program
MyServer.java
1. import java.io.*; // required data input/output stream
2. import java.net.*; //required for Socket Class
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(1111);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=
9. new DataInputStream (s.getInputStream());
10. String str=(String)dis.readUTF();
11. System.out.println("message= "+str);
12. ss.close();
13. }
14. catch(Exception e){System.out.println(e);}
15. }
16.}
Output
message= Hello Server Server

socket

Unit-1 JAVA NETWORKING 27 Darshan Institute of Engineering & Technology


TCP/IP Client Sockets: Socket Class
The client in socket programming must know two information:
1. IP Address of Server
2. Port number.
Constructor
Socket() Creates an unconnected socket
Socket(InetAddress address, int port) Creates a stream socket and connects it to the
specified port number at the specified IP
address.

Method
public InputStream getInputStream() returns the InputStream attached with this
socket
public OutputStream getOutputStream() returns the OutputStream attached with this
socket.

Unit-1 JAVA NETWORKING 28 Darshan Institute of Engineering & Technology


TCP/IP Client Sockets
Syntax
Socket myClient; //Creates object of Socket Class
myClient = new Socket("Machine name", PortNumber);

DNS or IP Address Port Number is the port


(a number) on which the
server you are trying to
connect.

Example
Socket s;
s=new Socket("localhost",1111);

Unit-1 JAVA NETWORKING 29 Darshan Institute of Engineering & Technology


TCP/IP Client Sockets: Program
1. import java.net.*; //required for Socket Class
2. import java.io.*; // required data input/output stream
3. public class MyClient {
4. public static void main(String[] args)
5. { try{
6. Socket s = new Socket("localhost",1111);
7. DataOutputStream dout= new Object of Socket class
DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");// Writes a
string to the underlying output stream
9. }catch(Exception e)
10. {System.out.println(e);}
11. }
12.}

Unit-1 JAVA NETWORKING 30 Darshan Institute of Engineering & Technology


TCP/IP Client-Server program
MyServer.java MyClient.java

import java.io.*; import java.net.*;


import java.net.*; import java.io.*;

public class MyServer { public class MyClient {


public static void main(String[] args){
public static void main(String[] args){
try{
try {
ServerSocket ss=new ServerSocket(1111);
Socket s=new Socket("localhost",1111);
Socket s=ss.accept();
DataOutputStream dout=new
DataInputStream dis=new DataInputStream DataOutputStream(s.getOutputStream());
(s.getInputStream());
String str=(String)dis.readUTF(); dout.writeUTF("Hello Server");
//Writes string to underlying o/p
System.out.println("message= "+str); stream
ss.close();
}//try
catch(Exception e)
}catch(Exception e)
{System.out.println(e);} {System.out.println(e);}
}//psvm } //psvm
}//class }//class

Output
message= Hello Server

Unit-1 JAVA NETWORKING 31 Darshan Institute of Engineering & Technology


Unit-1: Java Networking
Topic
1. Network Basics and Socket overview
2. InetAddress
3. TCP/IP server sockets
4. TCP/IP client sockets
5. Datagrams
6. URL
7. URLConnection

Unit-1 JAVA NETWORKING 32 Darshan Institute of Engineering & Technology


Datagrams
Java.net

InetAddress
URL
URLConnection
ServerSocket This class represents a
datagram packet.
Socket
DatagramPacket
Represents a socket for sending
UDP DatagramSocket and receiving datagram
packets.

Unit-1 JAVA NETWORKING 33 Darshan Institute of Engineering & Technology


Datagrams: DatagramSocket class
 DatagramSocket class represents a connection-less socket for
sending and receiving datagram packets.
 A datagram is basically an information but there is no guarantee of
its content, arrival or arrival time.
 Constructor
DatagramSocket() it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
DatagramSocket(int port) it creates a datagram socket and binds it with the given
Port Number.
DatagramSocket(int port, it creates a datagram socket and binds it with the
InetAddress address) specified port number and host address.

Unit-1 JAVA NETWORKING 34 Darshan Institute of Engineering & Technology


Datagrams: DatagramPacket class
 Java DatagramPacket is a message that can be sent or received.
 If you send multiple packet, it may arrive in any order.
 Additionally, packet delivery is not guaranteed.
number of bytes to
buffer for holding the incoming datagram. read.

Constructor
DatagramPacket(byte[] barr, int length) It creates a datagram packet. This
constructor is used to receive the packets.
DatagramPacket(byte[] barr, int length, It creates a datagram packet. This
InetAddress address, int port) constructor is used to send the packets.

Unit-1 JAVA NETWORKING 35 Darshan Institute of Engineering & Technology


Example of Sending DatagramPacket by DatagramSocket

import java.net.*; //required for Datagram Class


public class DSender{
public static void main(String[] args)
throws Exception
{
DatagramSocket ds = new DatagramSocket();
String str = "Message sent by Datagram socket";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket


(str.getBytes(), str.length(), ip, 3000);
ds.send(dp);
ds.close();
}
}

Unit-1 JAVA NETWORKING 36 Darshan Institute of Engineering & Technology


Example of Receiving DatagramPacket by DatagramSocket

import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception
{
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0,dp.getLength());
System.out.println(str);
ds.close();
}
}

Output
Message sent by Datagram socket

Unit-1 JAVA NETWORKING 37 Darshan Institute of Engineering & Technology


Example of Sending and Receiving DatagramPacket
DSender.java DReceiver.java
import java.net.*; import java.net.*;
public class DSender{ public class DReceiver{
public static void main(String[] args) public static void main(String[] args)
throws Exception{ throws Exception {

DatagramSocket ds= DatagramSocket ds =


new DatagramSocket(); new DatagramSocket(3000);
String str = "Message sent by Datagram byte[] buf = new byte[1024];
socket"; DatagramPacket dp =
InetAddress ip = new DatagramPacket(buf, 1024);
InetAddress.getByName("127.0.0.1");
ds.receive(dp);
DatagramPacket dp = new DatagramPacket String str = new String
(str.getBytes(),str.length(),ip,3000); (dp.getData(), 0,dp.getLength());

ds.send(dp); System.out.println(str);
ds.close(); ds.close();
}
} }
}
Output
Message sent by Datagram socket

Unit-1 JAVA NETWORKING 38 Darshan Institute of Engineering & Technology


Unit-1: Java Networking
Topic
1. Network Basics and Socket overview
2. InetAddress
3. TCP/IP client sockets
4. TCP/IP server sockets
5. Datagrams
6. URL
7. URLConnection

Unit-1 JAVA NETWORKING 39 Darshan Institute of Engineering & Technology


URL: Uniform Resource Locator
 The Java URL class represents an URL.
 This class is pointer to “resource” on the World Wide Web.
Port Number
E.g.
http is the http://10.255.1.1:8090/httpclient.html
protocol.

Server name or IP Address File Name or directory name

Unit-1 JAVA NETWORKING 40 Darshan Institute of Engineering & Technology


URL
Constructor

URL(String url) Creates a URL object from the String representation.

Example
URL url=new URL("http://www.gtu.ac.in");

Method
public URLConnection openConnection() This method of URL class returns the
throws IOException object of URLConnection class

Example
URLConnection urlcon=url.openConnection();

Unit-1 JAVA NETWORKING 41 Darshan Institute of Engineering & Technology


Unit-1: Java Networking
Topic
1. Network Basics and Socket overview
2. InetAddress
3. TCP/IP client sockets
4. TCP/IP server sockets
5. Datagrams
6. URL
7. URLConnection

Unit-1 JAVA NETWORKING 42 Darshan Institute of Engineering & Technology


URLConnection
 URLConnection is the superclass of all classes that represent a
communications link between the application and a URL.
 Instances of this class can be used both to read from and to write
to the resource referenced by the URL.
Constructor
URLConnection(URL url) Constructs a URL connection to the
specified URL

Unit-1 JAVA NETWORKING 43 Darshan Institute of Engineering & Technology


URLConnection
Method

public InputStream getInputStream() Returns an input stream that reads from this
throws IOException open connection.
public OutputStream getOutputStream() Returns an output stream that writes to this
throws IOException connection.

Unit-1 JAVA NETWORKING 44 Darshan Institute of Engineering & Technology


URLConnection : Program
import java.io.*; //required for input stream
import java.net.*; //required for URL & URLConnection
public class URLConnectionDemo {
public static void main(String[] args){
try{
URL url=new URL("http://www.gtu.ac.in");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i; Object of URLConnection Class
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}

Unit-1 JAVA NETWORKING 45 Darshan Institute of Engineering & Technology


Important Questions: GTU
1 What is Server Socket? Explain in detail with an example. Discuss the [Win-16]
difference between the Socket and ServerSocket class. [Win-17]
[Sum-18]
2 What is Datagram Socket? Explain in detail with example. [Win-16]
3 Write a TCP or UDP client and server program to do the following: [Sum-16]
Client send : Welcome to Gujarat Technological UNIVERSITY [Win-16]
Response from Server: ytisrevinu LACIGOLONHCEt TARAJUg TO EMOCLEw [Win-18]
4 Write a client-server program using TCP or UDP where the client sends 10 [Sum-16]
numbers and server responds with the numbers in sorted order.
5 Write a TCP Client-Server program to get the Date & Time details from [Sum-15]
Server on the Client request. [Win-16]
[Sum-19]
6 Write a client server program using TCP where client sends two numbers [Win-15]
and server responds with sum of them. [Win-17]
7 Write a client server program using TCP where client sends a string and [Sum-17]
server checks whether that string is palindrome or not and responds with [Sum-18]
appropriate message.

Unit-1 JAVA NETWORKING 46 Darshan Institute of Engineering & Technology


Important Questions: GTU
8 Write a sample code for client send a “Hello” message to server. [4] [Win-19]

9 Write a client-server program using TCP sockets to echo the message send by [Sum-19]
the client.[7]
10 Explain the following classes with their use. i. URLConnection class [Sum-19]
ii. DatagramSocket (iii) DatagramPacket class [3]

Unit-1 JAVA NETWORKING 47 Darshan Institute of Engineering & Technology

You might also like