0% found this document useful (0 votes)
24 views33 pages

Chapter 4 - Javanetworking

Chapter 4 of the document discusses Java Networking, focusing on the concepts of connecting computing devices and sharing resources through Java socket programming. It covers key terminologies such as IP address, protocol, port number, and the differences between connection-oriented (TCP) and connection-less (UDP) protocols, along with examples of socket programming. The chapter also explains the use of classes like InetAddress, DatagramPacket, and ServerSocket for network communication in Java.

Uploaded by

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

Chapter 4 - Javanetworking

Chapter 4 of the document discusses Java Networking, focusing on the concepts of connecting computing devices and sharing resources through Java socket programming. It covers key terminologies such as IP address, protocol, port number, and the differences between connection-oriented (TCP) and connection-less (UDP) protocols, along with examples of socket programming. The chapter also explains the use of classes like InetAddress, DatagramPacket, and ServerSocket for network communication in Java.

Uploaded by

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

Harambe

University

Chapter 4

Java Networking (Java net)

Computer Sc. Dept.


Java Networking
 JavaNetworking is a concept of connecting two or
more computing devices together so that we can
share resources.
 Java socket programming provides facility to share
data between different computing devices.
 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 Networking Terminology
The widely used java networking terminologies are given below:
 IP Address
 Protocol
 Port Number
 MAC Address
 Connection-oriented and connection-less protocol
 Socket
1. IP Address
 IP address is a unique number assigned to a node of a network
 It is a logical address that can be changed.
 is an identifier assigned to each computer and other device(e.g.,
router, mobile, etc)
2. Protocol
 A protocol is a set of rules basically that is
followed for communication.
For example:
 TCP: It is the most common protocol in networks
that use the Internet Protocol (IP).
 FTP
is a widely used network protocol for transferring
files between computers over a TCP/IP-based
network, such as the Internet.
 Telnet
A terminal emulation that enables a user to connect
to a remote host or device using a telnet client.
For example, typing telnet hostname would connect a
user to a hostname named hostname.
o SMTP
An SMTP (Simple Mail Transfer Protocol) server is
an application that's primary purpose is to send,
receive, and/or relay outgoing mail between
email senders and receivers
3. Port Number
The port number is used to uniquely identify
different applications. It acts as a
communication endpoint between applications.

4. MAC Address
MAC (Media Access Control) Address is a unique
identifier of NIC (Network Interface Controller).
A network node can have multiple NIC but each
with unique MAC
5. Connection-oriented and connection-less
protocol
In connection-oriented protocol, acknowledgement is
sent by the receiver. So it is reliable but slow.
The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is
not sent by the receiver. So it is not reliable but fast.
The example of connection-less protocol is UDP.

6. Socket
A socket is an endpoint between two way
communications.
A socket in Java is one endpoint of a two-way
communication link between two programs running on
the network.
InetAddress Class
 Inet Address is used to encapsulate both the
numerical IP address and the domain name for that
address.
 It can handle both IPv4 and Ipv6 addresses.
 An InetAddress class method corresponds to a
DNS request
 No public constructor
 Three static methods:
 InetAddress getByName(String)
o Static method used to retrieve the address for
the host name passed as the parameter.
 InetAddress [ ] getAllByName(String)
o Static method used to retrieve all the addresses
for the host name passed as a parameter.
 InetAddress getLocalHost( )
o Static method used to retrieve the address for
the current, or local host.
Cont…

 Java InetAddress class represents an IP address.


 java.net.InetAddress class provides methods to
get the IP of any host name for
example www.javatpoint.com, www.google.com,
www.facebook.com, etc.
 Three additional “getter” methods
 String getHostName( )
 Returns the host name.
 byte[ ] getAddress( )
 Returns the IP address.
 String getHostAddress( )
 Returns the IP address as a string.
InetAddress Examples

import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{

InetAddress ip=InetAddress.getByName("www.javatpoint.com"
);
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.javatpoint.com
IP Address: 206.51.231.148
Cont…
try
{ InetAddress fullname =
netAddress.getByName(“bigyellowcat.cs.binghamton
;
InetAddress alias =
InetAddress.getByName(“bigyellowcat"); InetAddre
octets = InetAddress.getByName(“128.226.121.44");
if (fullname.equals(alias) && fullname.equals(octe
// All is right with the world!
}
catch (UnknownHostException e)
{ // Exception handling here. }
TCP Sockets
 Once a TCP socket connection is made, a virtual stream is
in place. Java’s IO model is that of a stream, therefore
the models are consistent; all you need to do connect a
TCP socket to a stream and read and write the streams as
normal
 Sockets can be configured to act as a server and listen for
incoming messages, or connect to other applications as
a client. After both ends of a TCP/IP socket are connected,
communication is bi-directional.
 Socket
is one endpoint of a two-way communication link
between two programs running on the network.
is bound to a port number so that the TCP layer can
identify the application that data is destined to be sent
is simply an endpoint for communications between the
machines.
Socket Class - TCP Client sockets
 Socket(String ip, int port)
◦ Creates a streaming socket and binds it to the host and
port specified as parameters.
 Socket(String ip, int port, boolean TCP or UDP)
◦ Creates a socket and binds it to the host and port
specified as parameters. The last parameter is used to
indicate whether the socket should be a stream or
datagram socket.
 Socket(InetAddress ia, int port)
◦ Creates a streaming socket connected to the specified
host and port.
 Socket(InetAddress ia, int port, boolean TCPorUDP)
◦ Creates a socket connected to the specified host and
port. The last parameter specifies whether the socket
should be a stream or datagram socket.
Client Sockets
 Client sockets send messages to
server sockets by specifying the server endpoint
in a call to connect() and then sending data using
send() or write() .
 When the client calls connect() , a connection is
pushed onto the server-side queue where it sits
until the server accepts the connection
Client Sockets methods
 InetAddress getInetAddress( )
◦ Returns an InetAddress object representing the host for
this socket.
 Int getPort( )

◦ . Returns the port number on the remote host for this


socket
 Int getLocalPort( )

◦ Returns the port number on the local host for this socket.
 InputStream getInputStream( ) or need Read()

◦ Returns an input stream for the socket.


 OutputStream getOutputStream( ) use write()

◦ Returns an output stream for the socket.


 Close( )

◦ Closes the socket.


 SetSocketImplFactory (SocketImplFactory)

◦ Sets the socket factory that will be used to create all


sockets.
Example of Java Socket Programming Reading and
Writing both side
// File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(5454);
Socket s=ss.accept(); //establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
// File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",5454);
DataOutputStream dout=new DataOutputStream(s.getOutp
utStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
User Datagram Protocol (UDP ) Sockets
 Since UDP is a connectionless protocol; there is no virtual stream
between the hosts so streams are not used for IO.
 UDP applications are not thought of in terms of clients and servers,
but rather in terms of senders and receivers.
◦ For conversational applications both ends (sender and receiver)
will be changing states from sender to receiver and back again
◦ Many UDP based applications are simple send a request then
receive the data (sender’s perspective), like a DNS request. The
receiver’s perspective is to ‘listen’ for a request, send the
response, listen for more requests.
◦ DNS, or the Domain Name System, translates human readable
domain names to machine readable IP addresses.

 The UDP protocol provides a mode of network communication


whereby applications send packets of data, called datagrams, to
one another.
 The DatagramPacket and DatagramSocket classes in the java.net
package implement system-independent datagram communication
Datagram Packet Class
 UDP sockets send and receive Datagrams
 Constructors: two for receiving, four for sending

◦ DatagramPacket( byte[ ] buff , int len)


 Constructs a DatagramPacket for receiving packets of length
len.
◦ DatagramPacket(byte[] buf, int off, int len)
 Constructs a DatagramPacket for receiving packets of length
len, specifying an offset of off bytes into the buffer(data
stored in this datagram packet)
◦ DatagramPacket((byte[] buf, int len, InetAddress addr,
int port)
 Constructs a datagram packet for sending packets of length
len to the specified port number on the specified host.
◦ DatagramPacket(byte[] buf, int off, int len, InetAddress addr,
int port)
 Constructs a datagram packet for sending packets of length
len with offset off to the specified port number on the
DatagramPacket Class
◦ DatagramPacket(byte[] buf, int len, SocketAddress addr)
 Constructs a datagram packet for sending packets of
length len to the specified port number on the specified
host.
 Getter and setter methods are used to retrieve and
manipulate private variables in a different class. A
"getter" method does as it name suggest, retrieves a the
attribute of the same name. A setter method allows you to
set the value of the attribute.
Getter methods Setter methods
getAddress( ) setAddress(InetAddress iaddr)

getData( ) setData(byte[ ] buf)


getLength( ) setData(byte[] buf, int offset,
getOffset( ) int length)
getPort( ) setLength(int len)
DatagramSocket Class – UDP Sockets
 Constructors
• DatagramSocket()
 Constructs a datagram socket and binds it to any
available port on the local host.
• DatagramSocket(DatagramSocketImpl impl)
 Creates an unbound datagram socket with the specified
DatagramSocketImpl.
• DatagramSocket(int port)
 Constructs a datagram socket and binds it to the
specified port on the local host.
• DatagramSocket(int port, InetAddress iaddr)
 Creates a datagram socket, bound to the specified local
address.
• DatagramSocket(SocketAddress bindaddr)
 Creates a datagram socket, bound to the specified local
DatagramSocket Class – operational
Methods
 Operational (void) Methods
 bind(SocketAddress addr)
 connect(InetAddress address, int port)
 connect(SocketAddress addr)
 disconnect( )
 receive(DatagramPacket p)
 send(DatagramPacket p)
 close( )
DatagramSocket Class – getter methods
Getter Methods:
DatagramChannel getChannel( )
InetAddress getInetAddress( )
boolean getBroadcast( )
InetAddress getLocalAddress( )
int getLocalPort( )
SocketAddress getLocalSocketAddress( )
SocketAddress getRemoteSocketAddress( )
int getPort( )
int getReceiveBufferSize( )
int getSendBufferSize( )
boolean getReuseAddress( )
int getSoTimeout( )
DatagramSocket Class – setter methods

Setter Methods:
void setBroadcast( boolean on)
static void setDatagramSocketImplFactory
(DatagramSocketImplFactory fac)
void serReceiveBufferSize(int size)
void setReuseAddress(boolean on)
void setSevdBufferSize(int size)
void setSoTimeout(int timeout)
void setTrafficClass(int tc)
Java URL class
 A Class URL represents a Uniform Resource Locator,
which is a pointer to a “resource” on the World Wide Web.
For example:
https://www.javatpoint.com/java-tutorial

A URL contains many information:


 Protocol: In this case, http is the protocol.
 Server name or IP Address: In this case,
www.javatpoint.com is the server name.
 Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port
number. If port number is not mentioned in the URL
 File Name or directory name: In this case, index.jsp is
the file name.
Constructors of Java URL class
 URL(String spec)
◦ Creates a URL object from the String representation.
 URL(String protocol, String host, int port, String file)
◦ Creates a URL object from the specified protocol, host,
port number, and file.
 URL(String protocol, String host, int port, String file,
URLStreamHandler handler)
◦ Creates a URL object from the specified protocol, host,
port number, file, and handler.
 URL(String protocol, String host, String file)
◦ Creates a URL from the specified protocol name, host
name, and file name.
 URL(URL context, String spec)
◦ Creates a URL by parsing the given spec within a
specified context
 URL(URL context, String spec,
URLStreamHandler handler)
◦ Creates a URL by parsing the given spec with the
URL Class – Utility methods

int hashCode( )
URLConnection openConnection( )
InputStream openStream( )
boolean sameFile(URL other)
String toExternalForm( )
String toString( )
boolean equals(Object obj)
Example of Java URL class
// File Name: URLDemo
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-
tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
} catch(Exception e){System.out.println(e);}
}
}
ServerSocket
Used as the main connection point for some service
you wish to provide.
Once created, it listens for connection requests
then queues the request for disposition
On Unix/Linux you must be root to use

Java Socket Server Examples (TCP/IP)


 Create a server socket and bind it to a specific
port number.
 Listen for a connection from the client and accept it.
 Read data from the client via an InputStream
obtained from the client socket.
 Send data to the client via the
client socket's OutputStream.
 Close the connection with the client.
ServerSocket – Life cycle
A new ServerSocket is created on a particular port using a
ServerSocket( ) constructor.
The ServerSocket listens for incoming connection attempts
on that port using its accept( ) method. accept( ) blocks
until a client attempts to make a connection, at which
point accept( ) returns a Socket object connecting the
client and the server.
Depending on the type of server, either the Socket's
getInputStream( ) method, getOutputStream( ) method, or
both are called to get input and output streams that
communicate with the client.
The server and the client interact according to an agreed-
upon protocol until it is time to close the connection.
The server, the client, or both close the connection.
The server returns to step 2 and waits for the next
connection.
ServerSockets - threads
 Simultaneous requests are held in a queue, as each
request is removed from the queue and processed new
connections requests can be added to the queue.
Connection requests received while the queue is full will
be blocked.
 Some clients use multiple retries in this case as
queue space will usually open up pretty quickly.

 For simple protocols (DayTime) the queue can usually


handle all of the requests without problem
 For more complex protocols (HTTP) use a thread to
process each connection. Threads have less overhead
than spawning an entire child process.
ServerSocket - Constructors
 public
ServerSocket(int port) throws IOException,
BindException

 public ServerSocket(int port, int queueLength) throws


IOException, BindException
 public ServerSocket(int port, int queueLength,
InetAddress bindAddress) throws IOException
ServerSocket – methods
 accept( ) – accepts a connection request and creates
a socket to the remote user
 close( ) – close the server socket and wait for next
connection request
ServerSocket - example

ServerSocket server = new ServerSocket(5776);


while (true)
{
Socket connection = server.accept( );
OutputStreamWriter out =
new
OutputStreamWriter(connection.getOutputStream( )
);
out.write("You've connected to this server. Bye-
bye now.\r\n");
connection.close( );
}
Thank You !!!

You might also like