0% found this document useful (0 votes)
33 views

Web Technologies Unit 2 Part 2

The document discusses Java networking and summarizes: 1. Java networking allows connecting computing devices to share resources using socket programming and the java.net package, which provides low-level and high-level APIs. 2. The java.net package supports TCP and UDP protocols for reliable and unreliable communication. 3. Socket and ServerSocket classes provide connection-oriented programming while DatagramSocket and DatagramPacket classes provide connectionless programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Web Technologies Unit 2 Part 2

The document discusses Java networking and summarizes: 1. Java networking allows connecting computing devices to share resources using socket programming and the java.net package, which provides low-level and high-level APIs. 2. The java.net package supports TCP and UDP protocols for reliable and unreliable communication. 3. Socket and ServerSocket classes provide connection-oriented programming while DatagramSocket and DatagramPacket classes provide connectionless programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Web Technologies

UNIT 2- JAVA GUI, FILE STREAM AND CONCURRENCY


GUI Development using SWING – I/O Streams and Object Serialization – Generic
Collections – Concurrency – Thread States and Life Cycles – Thread Synchronization –
Java Networking
Java Networking
• concept of connecting two or more computing devices together so that we can share resources.
• socket programming provides facility to share data between different computing devices.
java.net package can be divided into two sections:
• A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets i.e.
bidirectional data communication mechanism and Interfaces i.e. network interfaces.
• A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier, URLs i.e.
Universal Resource Locator, and Connections i.e. connections to the resource pointed by URLs.
java.net package supports two protocols,
• TCP: Transmission Control Protocol provides reliable communication between the sender and
receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
• UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet of data
to be transferred along two or more nodes
Java Networking
• Socket programming is used for communication between
the applications running on different JRE.
• Can be connection-oriented or connection-less.
• Socket and ServerSocket classes connection-oriented
socket programming and DatagramSocket and
DatagramPacket classes connection-less socket
programming.

The client in socket programming must know two information:

• IP Address of Server, and


• Port number.
For eg., client sends a message to the server, server reads the
message and prints it.
Two classes are being used: Socket and ServerSocket.
The Socket class is used to communicate client and server. Through
this class, we can read and write message.
The ServerSocket class is used at server-side. The accept() method
of ServerSocket class blocks the console until the client is
connected.
After the successful connection of client, it returns the instance of
Socket at server-side.
Java Networking
Creating Server:
Socket class To create the server application, we need to create
• A socket is simply an endpoint for communications the instance of ServerSocket class.
between the machines. Choose any port number.eg., Here, we are using
6666 port number for the communication between
• The Socket class can be used to create a socket.
the client and server.
public InputStream getInputStream()returns the The accept() method waits for the client.
InputStream attached with this socket. If clients connects with the given port number, it
returns an instance of Socket.
public OutputStream getOutputStream()returns the
OutputStream attached with this socket.
Creating Client:
public synchronized void close()closes this socket To create the client application, we need to create
ServerSocket class the instance of Socket class.
we need to pass the IP address or hostname of the
The ServerSocket class can be used to create a server Server and a port number.
socket. we are using "localhost" because our server is
This object is used to establish communication with the running on same system.
clients. Socket s=new Socket("localhost",6666);

public Socket accept()returns the socket and establish a


connection between server and client.
public synchronized void close()closes the server socket.
Java Networking
import java.io.*;
import java.io.*; import java.net.*;
import java.net.*; public class MyClient {
public static void main(String[] args) {
public class MyServer {
try{
public static void main(String[] args){ Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.get
try{
OutputStream());
ServerSocket ss=new ServerSocket(6666); dout.writeUTF("Hello Server");
Socket s=ss.accept();//establishes connection dout.flush();
dout.close();
DataInputStream dis=new DataInputStream(s.getInputStream s.close();
()); }catch(Exception e){System.out.println(e);}
String str=(String)dis.readUTF(); }
}
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
Java Networking URL(String spec)
Creates an instance of a URL from the String
URL class represents an URL. representation.
URL  Uniform Resource Locator. It points to a resource URL(String protocol, String host, int port, String file)
on the World Wide Web. Creates an instance of a URL from the given protocol,
host, port number, and file.
https://www.mitindia.edu/en/mitaa-activities
URL(String protocol, String host, int port, String file,
URLStreamHandler handler)
• Protocol: In this case, http is the protocol. Creates an instance of a URL from the given protocol,
host, port number, file, and handler.
• Server name or IP Address: In this case, URL(String protocol, String host, String file)
www.mitindia.edu is the server name. Creates an instance of a URL from the given protocol
• Port Number: It is an optional attribute. 80 is the port name, host name, and file name.
number. URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec
If port number is not mentioned in the URL, it within a specified context.
returns -1. URL(URL context, String spec, URLStreamHandler
• File Name or directory name: In this case, mitaa- handler)
activities is the file name. Creates an instance of a URL by parsing the given spec
with the specified handler within a given context.
Java Networking import java.net.*;
Method Description
public class URLDemo{
public static void main(String[] args){
public String getProtocol() it returns the protocol of the URL.
try{
public String getHost() it returns the host name of the URL.
URL url=new URL("https://www.google.com/search?
public String getPort() it returns the Port Number of the URL.
q=mitindia&oq=mitindia&sourceid=chrome&ie=UTF-
public String getFile() it returns the file name of the URL.
8");
public String getAuthority() it returns the authority of the URL.
public String toString() it returns the string representation of the URL. System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
public String getQuery() it returns the query string of the URL.
System.out.println("Port Number: "+url.getPort());
public String getDefaultPort() it returns the default port of the URL. System.out.println("Default Port Number:
public URLConnection it returns the instance of URLConnection i.e. "+url.getDefaultPort());
openConnection() associated with this URL.
System.out.println("Query String: "+url.getQuery());
public boolean equals(Object obj) it compares the URL with the given object.
System.out.println("Path: "+url.getPath());
public Object getContent() it returns the content of the URL.
System.out.println("File: "+url.getFile());
public String getRef() it returns the anchor or reference of the URL.
public URI toURI() it returns a URI of the URL.
}catch(Exception e){System.out.println(e);}
}
}
Java Networking public static InetAddress getByName(String host)
throws UnknownHostExceptionIt returns the instance
• Java InetAddress class represents an IP address.
of InetAddress containing LocalHost IP and name.
• provides methods to get the IP of any host name for example public static InetAddress getLocalHost() throws
www.google.com, www.facebook.com, etc. UnknownHostExceptionIt returns the instance of
• An IP address is represented by 32-bit or 128-bit unsigned InetAdddress containing local host name and address.
number. public String getHostName()It returns the host name
• An instance of InetAddress represents the IP address with its of the IP address.
corresponding host name. public String getHostAddress()It returns the IP
address in string format.
• There are two types of addresses: Unicast and Multicast.
• The Unicast is an identifier for a single interface whereas
• Multicast is an identifier for a set of interfaces.
• Moreover, InetAddress has a cache mechanism to store
successful and unsuccessful host name resolutions.
• InetAddress class is used to encapsulate both, the numerical
IP address and the domain name for that address.
• The InetAddress class has no visible constructors. The
InetAddress class has the inability to create objects directly,
hence factory methods are used for the purpose.
• Factory Methods are static methods in a class that return an
object of that class.
Java Networking DatagramSocket() throws SocketException: it creates a
datagram socket and binds it with the available Port
DatagramSocket and DatagramPacket
Number on the localhost machine.
Used for connection-less socket programming using the UDP DatagramSocket(int port) throws SocketException: it
instead of TCP. creates a datagram socket and binds it with the given
Datagrams are collection of information sent from one Port Number.
device to another device via the established network. DatagramSocket(int port, InetAddress address) throws
SocketException: it creates a datagram socket and
When the datagram is sent to the targeted device, there is binds it with the specified port number and host
no assurance that it will reach to the target device safely address.
and completely.
It may get damaged or lost in between. Likewise, the
receiving device also never know if the datagram received is
damaged or not.
The UDP protocol is used to implement the datagrams in
Java.
DatagramSocket class represents a connection-less socket
for sending and receiving datagram packets.
It is a mechanism used for transmitting datagram packets
over network.
A datagram is basically an information but there is no
guarantee of its content, arrival or arrival time.
Java Networking
Method Description
void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.
void close() It closes the datagram socket.
void connect(InetAddress address, int port) It connects the socket to a remote address for the socket.
void disconnect() It disconnects the socket.
boolean getBroadcast() It tests if SO_BROADCAST is enabled.
DatagramChannel getChannel() It returns the unique DatagramChannel object associated with the datagram socket.

InetAddress getInetAddress() It returns the address to where the socket is connected.


InetAddress getLocalAddress() It gets the local address to which the socket is connected.
int getLocalPort() It returns the port number on the local host to which the socket is bound.

SocketAddress getLocalSocketAddress() It returns the address of the endpoint the socket is bound to.
int getPort() It returns the port number to which the socket is connected.
int getReceiverBufferSize() It gets the value of the SO_RCVBUF option for this DatagramSocket that is the buffer size
used by the platform for input on the DatagramSocket.

boolean isClosed() It returns the status of socket i.e. closed or not.


boolean isConnected() It returns the connection state of the socket.
void send(DatagramPacket p) It sends the datagram packet from the socket.
void receive(DatagramPacket p) It receives the datagram packet from the socket.
Java Networking
Method Description

• DatagramPacket is a message that can be sent or 1) InetAddress getAddress() It returns the IP address of the machine to
which the datagram is being sent or from
received. which the datagram was received.

• It is a data container. 2) byte[] getData() It returns the data buffer.


3) int getLength() It returns the length of the data to be sent or
• If you send multiple packet, it may arrive in any order. the length of the data received.

Additionally, packet delivery is not guaranteed. 4) int getOffset() It returns the offset of the data to be sent or
the offset of the data received.
• Commonly used Constructors of DatagramPacket class 5) int getPort() It returns the port number on the remote
host to which the datagram is being sent or
• DatagramPacket(byte[] barr, int length): it creates a from which the datagram was received.
datagram packet. This constructor is used to receive the
packets. 6) SocketAddress getSocketAddress() It gets the SocketAddress (IP address + port
number) of the remote host that the packet
• DatagramPacket(byte[] barr, int length, InetAddress is being sent to or is coming from.

address, int port): it creates a datagram packet. This 7) void setAddress(InetAddress iaddr) It sets the IP address of the machine to
which the datagram is being sent.
constructor is used to send the packets.
8) void setData(byte[] buff) It sets the data buffer for the packet.

9) void setLength(int length) It sets the length of the packet.


10) void setPort(int iport) It sets the port number on the remote host to
which the datagram is being sent.

11) void setSocketAddress(SocketAddress It sets the SocketAddress (IP address + port


addr) number) of the remote host to which the
datagram is being sent.
Java Networking //Receiver
import java.net.*;
//sender public class DReceiver{
import java.net.*; public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
public class DSender{
byte[] buf = new byte[1024];
public static void main(String[] args) throws Exception { DatagramPacket dp = new DatagramPacket(buf, 1024);
DatagramSocket ds = new DatagramSocket(); ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1"); System.out.println(str);
ds.close();
DatagramPacket dp = new DatagramPacket(str.getBytes(), }
str.length(), ip, 3000); }
ds.send(dp);
ds.close();
}
}

You might also like