Chapter 2
Chapter 2
Java Networking
1
Introduction
Java Networking 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 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
2
Java Networking Terminology
The widely used Java networking terminologies are given below:
957
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
3
Con…
IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is
composed of octets that range from 0 to 255.
It is a logical address that can be changed.
Protocol
A protocol is a set of rules basically that is followed for communication. For example:
TCP
FTP
Telnet
SMTP
POP etc.
4
Con…
Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between
two applications.
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 address.
For example, an ethernet card may have a MAC address of
00:0d:83::b1:c0:8e.
5
Con…
Socket
A socket is an endpoint between two way communications.
Visit next page for Java socket programming.
java.net package
The 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.
The java.net package provides many classes to deal with networking
applications in Java. A list of these classes is given below:
6
Java Socket Programming
Java Socket programming is used for communication between the
applications running on different JRE.
Java Socket programming can be connection-oriented or connection-
less.
Socket and ServerSocket classes are used for connection-oriented
socket programming and DatagramSocket and DatagramPacket classes
are used for connection-less socket programming.
7
Con…
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
Here, we are going to make one-way client and server communication.
In this application, client sends a message to the server, server reads the message and prints
it.
Here, 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.
8
9
Con…
Socket class
A socket is simply an endpoint for communications between the
machines.
The Socket class can be used to create a socket.
Important methods
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this
socket.
3) public synchronized void close() closes this socket
10
Con…
ServerSocket class
The ServerSocket class can be used to create a server socket. This
object is used to establish communication with the clients.
Important methods
Method Description
1) public Socket accept() returns the socket and establish a connection
between server and client.
2) public synchronized void close() closes the server socket.
11
Example of Java Socket Programming
Creating Server:
To create the server application, we need to create the instance of
ServerSocket class.
Here, we are using 9999 port number for the communication between
the client and server.
You may also choose any other port number.
The accept() method waits for the client.
If clients connects with the given port number, it returns an instance
of Socket.
ServerSocket ss=new ServerSocket(9999);
Socket s=ss.accept();//establishes connection and waits for the client
12
Con…
Creating Client:
To create the client application, we need to create the instance of
Socket class.
Here, we need to pass the IP address or hostname of the Server and a
port number.
Here, we are using "localhost" because our server is running on same
system.
Socket s=new Socket("localhost",6666);
13
Let's see a simple of Java socket programming where client sends a text and server receives and prints it.
• //File: MyClient.java
//File: MyServer.java import java.io.*;
import java.io.*; import java.net.*;
import java.net.*; public class MyClient {
public class MyServer {
public static void main(String[] args) {
public static void main(String[] args){
try{
try{
Socket s=new Socket("localhost",9999);
ServerSocket ss=new ServerSocket(9999);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());dout.writeUTF("Hello Server");
String str=(String)dis.readUTF(); dout.flush();
System.out.println("message= "+str); dout.close();
ss.close(); s.close();
}catch(Exception e){System.out.println(e);} }catch(Exception e){System.out.println(e);}
} }
} }
14
Example of Java Socket Programming (Read-
Write both side)
In this example, client will write first to the server then server will
receive and print the text.
Then server will write to the client and client will receive and print
the text. The step goes on.
15
//File: MyServer.java //File: MyClient.java
} }}
din.close();
s.close();
16
ss.close();
Java URL
The Java URL class represents an URL. URL is an acronym for
Uniform Resource Locator. It points to a resource on the World Wide
Web. For example:
https://www.javatpoint.com/java-tutorial
17
Con…
A URL contains many information:
1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.javatpoint.com is the server
name.
3. 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, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.
18
Con…
Constructors of Java URL class
URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler
handler)
Creates an instance of a URL from the given protocol, host, port number, file, and
handler.
URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file
name.
URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.
19
• Commonly used methods of Java URL class
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public String getAuthority() it returns the authority of the URL.
public String toString() it returns the string representation of the
URL.
20
Con….
public String getQuery() it returns the query string of the URL.
public boolean equals(Object obj) it compares the URL with the given object.
21
Example of Java URL class
//URLDemo.java
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);}
}
}
22
example 2
//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("https://www.google.com/search?q=javatpoint&oq=javatpoint&sourceid=chrome&ie=UTF-
8");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("Default Port Number: "+url.getDefaultPort());
System.out.println("Query String: "+url.getQuery());
System.out.println("Path: "+url.getPath());
System.out.println("File: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
23
Java URLConnection Class
25
url Constructors
Constructor Description
1) protected URLConnection(URL url) It constructs a URL connection to the specified URL.
Method Description
void addRequestProperty(String key, String It adds a general request property specified by a key-value pair
value)
void connect() It opens a communications link to the resource referenced by this
URL, if such a connection has not already been established.
boolean getAllowUserInteraction() It returns the value of the allowUserInteraction field for the object.
long getContentLengthLong() It returns the value of the content-length header field as long.
static boolean getDefaultAllowUserInteraction() It returns the default value of the allowUserInteraction field.
27
Con…
boolean getDoInput() It returns the value of the URLConnection's doOutput flag.
static FileNameMap getFilenameMap() It loads the filename map from a data file.
String getHeaderField(String name) It returns the value of the named header field.
long getHeaderFieldDate(String name, long It returns the value of the named field parsed as a number.
Default)
int getHeaderFieldInt(String name, int Default) It returns the value of the named field parsed as a number.
String getHeaderFieldKey(int n) It returns the key for the nth header field.
long getHeaderFieldLong(String name, long It returns the value of the named field parsed as a number.
Default)
28
Con…
Map<String,List<String>> It returns the unmodifiable Map of the header field.
getHeaderFields()
long getIfModifiedSince() It returns the value of the object's ifModifiedSince field.
InputStream getInputStream() It returns an input stream that reads from the open condition.
long getLastModified() It returns the value of the last-modified header field.
OutputStream getOutputStream() It returns an output stream that writes to the connection.
Permission getPermission() It returns a permission object representing the permission
necessary to make the connection represented by the object.
int getReadTimeout() It returns setting for read timeout.
29
Con…
Map<String,List<String>>getRequestProperties() It returns the value of the named general request
property for the connection.
URL getURL() It returns the value of the URLConnection's URL
field.
boolean getUseCaches() It returns the value of the URLConnection's
useCaches field.
Static String guessContentTypeFromName(String It tries to determine the content type of an object,
fname) based on the specified file component of a URL.
static String It tries to determine the type of an input stream
guessContentTypeFromStream(InputStream is) based on the characters at the beginning of the
input stream.
void setAllowUserInteraction(boolean It sets the value of the allowUserInteraction field
allowuserinteraction) of this URLConnection.
30
Con…
Static void It sets the ContentHandlerFactory of an application.
setContentHandlerFactory(ContentHandlerFactory fac)
void steDafaultUseCaches(boolean defaultusecaches) It sets the default value of the useCaches field to the
specified value.
void setDoInput(boolean doinput) It sets the value of the doInput field for this
URLConnection to the specified value.
void setDoOutput(boolean dooutput) It sets the value of the doOutput field for the
URLConnection to the specified value.
31
How to get the object of URLConnection Class
32
Example of Java URLConnection Class
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
33
The Java HttpURLConnection class is http specific URLConnection.
It works for HTTP protocol only.
By the help of HttpURLConnection class, you can retrieve information of any
HTTP URL such as header information, status code, response code etc.
The java.net.HttpURLConnection is subclass of URLConnection class.
HttpURLConnection Class Constructor
Constructor Description
protected HttpURLConnection(URL u) It constructs the instance of HttpURLConnection class.
34
Method Description
void disconnect() It shows that other requests from the server are unlikely in the
near future.
InputStream getErrorStream() It returns the error stream if the connection failed but the server
sent useful data.
Static boolean getFollowRedirects() It returns a boolean value to check whether or not HTTP
redirects should be automatically followed.
String getHeaderField(int n) It returns the value of nth header file.
long getHeaderFieldDate(String name, long Default) It returns the value of the named field parsed as a date.
String getHeaderFieldKey(int n) It returns the key for the nth header file.
35
String getRequestMethod() It gets the request method.
int getResponseCode() It gets the response code from an HTTP response
message.
String getResponseMessage() It gets the response message sent along with the
response code from a server.
void setChunkedStreamingMode(int chunklen) The method is used to enable streaming of a HTTP
request body without internal buffering, when the
content length is not known in advance.
void setFixedLengthStreamingMode(int contentlength) The method is used to enable streaming of a HTTP
request body without internal buffering, when the
content length is known in advance.
void setFixedLengthStreamingMode(long The method is used to enable streaming of a HTTP
contentlength) request body without internal buffering, when the
content length is not known in advance.
static void setFollowRedirects(boolean set) It sets whether HTTP redirects (requests with response
code) should be automatically followed by
HttpURLConnection class.
36
Con…
void setInstanceFollowRedirects(boolean It sets whether HTTP redirects (requests with response code)
followRedirects) should be automatically followed by instance of
HttpURLConnection class.
void setRequestMethod(String method) Sets the method for the URL request, one of: GET POST
HEAD OPTIONS PUT DELETE TRACE are legal, subject to
protocol restrictions.
abstract boolean usingProxy() It shows if the connection is going through a proxy.
Syntax:
1.public URLConnection openConnection()throws IOExceptio
n{}
You can typecast it to HttpURLConnection type as given below.
2.URL url=new URL("http://www.javatpoint.com/java-
tutorial");
3.HttpURLConnection huc=(HttpURLConnection)url.openCon
nection();
37
How to get the object of HttpURLConnection
class
The openConnection() method of URL class returns the object of
URLConnection class.
Syntax:
public URLConnection openConnection()throws IOException{}
38
Java HttpURLConnection Example
import java.io.*;
import java.net.*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));
}
huc.disconnect();
}catch(Exception e){System.out.println(e);}
}
} 39
Java InetAddress class
Java InetAddress class represents an IP address.
The 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
An instance of InetAddress represents the IP address with its corresponding host
name.
There are two types of addresses:
Unicast
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
40
host name resolutions.
Java InetAddress Class Methods
Method Description
41
Example of Java InetAddress Class
Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com
website.
//InetDemo.java
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
45
Java DatagramSocket Class
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, It connects the socket to a remote address for the socket.
int port)
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. 46
Con…
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.
48
Java DatagramPacket Class Methods
Method Description
InetAddress getAddress() It returns the IP address of the machine to which the datagram
is being sent or from which the datagram was received.
byte[] getData() It returns the data buffer.
int getLength() It returns the length of the data to be sent or the length of the
data received.
int getOffset() It returns the offset of the data to be sent or the offset of the
data received.
int getPort() It returns the port number on the remote host to which the
datagram is being sent or from which the datagram was
received.
SocketAddress It gets the SocketAddress (IP address + port number) of the
getSocketAddress() remote host that the packet is being sent to or is coming from.
49
Con…
void setAddress(InetAddress iaddr) It sets the IP address of the machine to which
the datagram is being sent.
void setData(byte[] buff) It sets the data buffer for the packet.
void setPort(int iport) It sets the port number on the remote host to
which the datagram is being sent.
50
Example of Sending DatagramPacket by
DatagramSocket
//DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");