Java Network Programming getting started, Getting Started with java network programming, two tier architecture, java client server programming, core java, java to standard edition, core java, Introduction to network programming in java
3. ADVANCE JAVA
Author Profile
Ankit Desai
Ph.D. Scholar, IET, Ahmedabad University
Education: M. Tech. (C.E.), B. E. (I. T.)
Experience: 8 years (Academic and Research)
Research Interest: IoT, Big Data Analytics, Machine
Learning, Data Mining, Algorithms.
Classified e-Material 3
4. ADVANCE JAVA
Classified e-Material 4
InetAddress CLASS
The Inetaddress class provides you with a limited
interface to DNS for doing both forward and
reverse internet address lookups
An InetAddress class method corresponds to a DNS
request
5. ADVANCE JAVA
Classified e-Material 5
InetAddress CLASS
No public constructor
Static methods:
static InetAddress[] getAllByName (String host)
Static method used to retrieve all the addresses for the
host name passed as a parameter.
static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .
static InetAddress getByAddress (String host,
byte[] addr)
Create an InetAddress based on the provided host name
and IP address No name service is checked for the validity
of the address.
6. ADVANCE JAVA
Classified e-Material 6
static InetAddress getByName(String)
Static method used to retrieve the address for the host
name passed as the parameter.
static InetAddress getLocalHost( )
Static method used to retrieve the address for the
current, or local, host.
7. ADVANCE JAVA
Classified e-Material 7
InetAddress Class
Additional “getter” methods
byte[ ] getAddress()
Returns the IP address.
String getHostAddress()
Returns the IP address as a string.
String getHostName()
Returns the host name.
9. ADVANCE JAVA
Classified e-Material 9
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.
10. ADVANCE JAVA
Classified e-Material 10
JAVA TCP Sockets
In Package java.net
java.net.Socket
Implements client sockets (also called just “sockets”).
An endpoint for communication between two
machines.
Constructor and Methods
Socket(String host, int port): Creates a stream socket
and connects it to the specified port number on the
named host.
InputStream getInputStream()
OutputStream getOutputStream()
close()
11. ADVANCE JAVA
Classified e-Material 11
java.net.ServerSocket
Implements server sockets.
Waits for requests to come in over the network.
Performs some operation based on the request.
Constructor and Methods
ServerSocket(int port)
Socket Accept(): Listens for a connection to be made to this
socket and accepts it. This method blocks until a connection
is made.
12. ADVANCE JAVA
Classified e-Material 12
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 TCPorUDP)
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.
13. ADVANCE JAVA
Classified e-Material 13
Client Sockets (Methods)
InetAddress getInetAddress( )
Returns the address to which the socket is connected
int getPort( )
Returns the port number on the remote host for this
socket
InetAddress getLocalAddress( )
Gets the local address to which the socket is bound.
int getLocalPort( )
Returns the port number on the local host for this
socket.
InputStream getInputStream( )
Returns an input stream for the socket.
OutputStream getOutputStream( )
Returns an output stream for the socket.
void close()
Closes the socket.
14. ADVANCE JAVA
Classified e-Material 14
Client Sockets (Methods)
int GetSoLinger()
void setSoLinger(boolean on, int linger)
This option sets how long a socket is remain open
after a close() method has been invoked and data
remains to be sent over the socket
public int getSoTimeout()
public void setSoTimeout(int timeout)
this option set to a non-zero timeout, a read() call on
the InputStream associated with this Socket will block
for only this amount of time
15. ADVANCE JAVA
Classified e-Material 15
Client Sockets (Methods)
public void setTcpNoDelay(boolean on)
public boolean getTcpNoDelay()
Option is used to specify Nagle’s algorithm should
be used to buffer data that is sent over a socket
connection.
16. ADVANCE JAVA
Classified e-Material 16
ServerSocket class- Constructors
public ServerSocket(int port) throws IOException
Creates a server socket, bound to the specified port.
public ServerSocket(int port, int backlog) throws
IOException
Creates a server socket and binds it to the specified local
port number, with the specified backlog.
public ServerSocket(int port, int backlog, InetAddress
networkInterface) throws IOException
Create a server with the specified port, listen backlog,
and local IP address to bind to.
17. ADVANCE JAVA
Classified e-Material 17
ServerSocket class- Methods
public Socket accept() throws IOException
Listens for a connection to be made to this socket and
accepts it. The method blocks until a connection is
made
public void close() throws IOException
Closes this socket. Any thread currently blocked in
accept() will throw a SocketException
public InetAddress getInetAddress()
Returns the local address of this server socket
public void bind(SocketAddress endpoint) throws
IOException
Binds the ServerSocket to a specific address (IP
address and port number)
18. ADVANCE JAVA
Classified e-Material 18
ServerSocket class- Methods
public int getLocalPort()
Returns the port on which this socket is listening.
public SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is bound
to, or null if it is not bound yet.
protected final void implAccept(Socket s) throws
IOException
Subclasses of ServerSocket use this method to override
accept() to return their own subclass of socket.
public boolean isBound()
Returns the binding state of the ServerSocket.
public boolean isClosed()
Returns the closed state of the ServerSocket
19. ADVANCE JAVA
Classified e-Material 19
ServerSocket class- Methods
public void setSoTimeout(int timeout) throws
SocketException
Enable/disable SO_TIMEOUT with the specified timeout,
in milliseconds. With this option set to a non-zero
timeout, a call to accept() for this ServerSocket will
block for only this amount of time. If the timeout
expires, a java.net.SocketTimeoutException is
raised, though the ServerSocket is still valid
public int getSoTimeout() throws IOException
Retrive setting for SO_TIMEOUT. 0 returns implies that
the option is disabled
public void setReuseAddress(boolean on) throws
SocketException
Enable/disable the SO_REUSEADDR socket option
21. ADVANCE JAVA
Classified e-Material 21
Implementing a Server
1. Open the Server Socket:
ServerSocket server;
DataOutputStream os;
DataInputStream is;
server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
is = new DataInputStream( client.getInputStream());
os = new DataOutputStream( client.getOutputStream());
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes("Hellon");
5. Close sockets: client.close();
22. ADVANCE JAVA
Classified e-Material 22
For multithreaded server:
while(true) {
i. wait for client requests (step 2 above)
ii. create a thread with “client” socket as
parameter (the thread creates streams (as in
step (3) and does communication as stated in
(4). Remove thread once service is provided.
}
23. ADVANCE JAVA
Classified e-Material 23
Implementing a Client
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server:
is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream(client.getOutputStream() );
3. Perform I/O or communication with the server:
Receive data from the server:
String line = is.readLine();
Send data to the server:
os.writeBytes("Hellon");
4. Close the socket when done:
client.close();
26. ADVANCE JAVA
Classified e-Material 26
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.
27. ADVANCE JAVA
Classified e-Material 27
DatagramPacket 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.
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.
28. ADVANCE JAVA
Classified e-Material 28
DatagramPacket(byte[] buf, int off, int len,
SocketAddress addr)
Constructs a datagram packet for sending packets of
length len with offset off to the specified port number
on the specified host.
DatagramPacker(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 specified host.
29. ADVANCE JAVA
Classified e-Material 29
DatagramPacket Class- Methods
public InetAddress getAddress()
Returns the IP address of the machine to which this
datagram is being sent or from which the datagram
was received.
public int getPort()
Returns the port number on the remote host to which
this datagram is being sent or from which the
datagram was received.
public byte[] getData()
Returns the data buffer. The data received or the data
to be sent starts from the offset in the buffer, and runs
for length long.
public int getOffset()
Returns the offset of the data to be sent or the offset
of the data received.
30. ADVANCE JAVA
Classified e-Material 30
DatagramPacket Class- Methods
public int getLength()
Returns the length of the data to be sent or the
length of the data received.
public void setData(byte[] buf, int offset, int length)
Set the data buffer for this packet. This sets the
data, length and offset of the packet.
public void setAddress(InetAddress iaddr)
Sets the IP address of the machine to which this
datagram is being sent.
public void setPort(int iport)
Sets the port number on the remote host to which
this datagram is being sent.
31. ADVANCE JAVA
Classified e-Material 31
DatagramPacket Class- Methods
public void
setSocketAddress(SocketAddress address)
Sets the SocketAddress (usually IP address + port
number) of the remote host to which this datagram
is being sent.
public SocketAddress getSocketAddress()
Gets the SocketAddress (usually IP address + port
number) of the remote host that this packet is
being sent to or is coming from.
public void setData(byte[] buf)
Set the data buffer for this packet. With the offset
of this DatagramPacket set to 0, and the length set
to the length of buf.
32. ADVANCE JAVA
Classified e-Material 32
public void setLength(int length)
Set the length for this packet. The length of the
packet is the number of bytes from the packet's data
buffer that will be sent, or the number of bytes of the
packet's data buffer that will be used for receiving
data. The length must be lesser or equal to the offset
plus the length of the packet's buffer.
33. ADVANCE JAVA
Classified e-Material 33
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 socket
address.
34. ADVANCE JAVA
Classified e-Material 34
DatagramSocket Class –Methods
public void bind(SocketAddress addr) throws
SocketException
Binds this DatagramSocket to a specific address &
port.
public void connect(InetAddress address, int port)
Connects the socket to a remote address for this
socket.
public void connect(SocketAddress addr) throws
SocketException
Connects this socket to a remote socket address (IP
address + port number).
public void disconnect()
Disconnects the socket. This does nothing if the
socket is not connected.
35. ADVANCE JAVA
Classified e-Material 35
DatagramSocket Class –Methods
public boolean isBound()
Returns the binding state of the socket.
public boolean isConnected()
Returns the connection state of the socket.
public InetAddress getInetAddress()
Returns the address to which this socket is
connected. Returns null if the socket is not
connected.
public int getPort()
Returns the port for this socket. Returns -1 if the
socket is not connected.
36. ADVANCE JAVA
Classified e-Material 36
DatagramSocket Class –Methods
public SocketAddress getRemoteSocketAddress()
Returns the address of the endpoint this socket is
connected to, or null if it is unconnected.
public SocketAddress getLocalSocketAddress()
Returns the address of the endpoint this socket is
bound to, or null if it is not bound yet.
public void send(DatagramPacket p) throws
IOException
Sends a datagram packet from this socket.
public void receive(DatagramPacket p) throws
IOException
Receives a datagram packet from this socket.
37. ADVANCE JAVA
Classified e-Material 37
DatagramSocket Class –Methods
public InetAddress getLocalAddress()
Gets the local address to which the socket is bound
public int getLocalPort()
Returns the port number on the local host to which
this socket is bound
public void setSoTimeout(int timeout) throws
SocketException
Enable/disable SO_TIMEOUT with the specified
timeout, in milliseconds
public int getSoTimeout() throws SocketException
Retrive setting for SO_TIMEOUT. 0 returns implies
that the option is disabled
38. ADVANCE JAVA
Classified e-Material 38
DatagramSocket Class –Methods
public void setSendBufferSize(int size) throws
SocketException
Sets the SO_SNDBUF option to the specified value for
this DatagramSocket
public int getSendBufferSize() throws
SocketException
Get value of the SO_SNDBUF option for this
DatagramSocket, that is the buffer size used by the
platform for output on this DatagramSocket
public void setReceiveBufferSize(int size) throws
SocketException
Sets the SO_RCVBUF option to the specified value for
this DatagramSocket
public int getReceiveBufferSize() throws
SocketException
Get value of the SO_RCVBUF option for this
DatagramSocket, that is the buffer size used by the
platform for input on this DatagramSocket
39. ADVANCE JAVA
Classified e-Material 39
Multicast Example
DatagramSocket socket = new DatagramSocket();
byte[] b = new byte[DGRAM_LENGTH];
DatagramPacket dgram;
dgram = new DatagramPacket(b, b.length,
InetAddress.getByName(MCAST_ADDR), DEST_PORT);
System.err.println("Sending " + b.length + " bytes to " +
dgram.getAddress() + ':' + dgram.getPort());
while(true) {
System.err.print(".");
socket.send(dgram);
Thread.sleep(1000);
}
40. ADVANCE JAVA
Classified e-Material 40
Multicast Example
byte[] b = new byte[BUFFER_LENGTH];
DatagramPacket dgram = new DatagramPacket(b,
b.length);
MulticastSocket socket = new
MulticastSocket(DEST_PORT); // must bind receive side
socket.joinGroup(InetAddress.getByName(MCAST_ADDR));
while(true) {
socket.receive(dgram); // blocks until a datagram is
received System.err.println("Received " +
dgram.getLength() + " bytes from " +
dgram.getAddress());
dgram.setLength(b.length); // must reset length field!
}
41. ADVANCE JAVA
Classified e-Material 41
URL Class
Represents a Uniform Resource Locator, a pointer
to a "resource" on the World Wide Web.
Consist of a protocol, host name, path and file
name.
Example:
http://archive.ncsa.uiuc.edu/SDG/Software/Mosaic/Demo/
It may contains either relative or absolute path of
file.
42. ADVANCE JAVA
Classified e-Material 42
URL Class - Constructors
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.
43. ADVANCE JAVA
Classified e-Material 43
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
specified handler within a specified context.
44. ADVANCE JAVA
Classified e-Material 44
URL Class - Methods
Object getContent()
Gets the contents of this URL.
Int getDefaultPort()
Gets the default port number of the protocol
associated with this URL.
String getFile()
Gets the file name of this URL
String getHost()
Gets the host name of this URL, if applicable.
String getPath()
Gets the path part of this URL.
45. ADVANCE JAVA
Classified e-Material 45
URL Class - Methods
int getPort()
Gets the port number of this URL.
String getProtocol()
Gets the protocol name of this URL.
String getQuery()
Gets the query part of this URL
InputStream openStream()
Opens a connection to this URL and returns an
InputStream for reading from that connection.
protected void set(String protocol, String host,
int port, String file, String ref)
Sets the fields of the URL.
protected void set(String protocol, String host,
int port, String authority, String userInfo, String path,
String query, String ref)
Sets the specified 8 fields of the URL.
46. ADVANCE JAVA
Classified e-Material 46
URL Class - example
import java.lang.System;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.*;
public class GetURLApp {
public static void main(String args[]){
try{ if(args.length!=1) error("Usage: java GetURLApp
URL");
System.out.println("Fetching URL: "+args[0]);
URL url = new URL(args[0]);
BufferedReader inStream = new BufferedReader( new
InputStreamReader(url.openStream()));
48. ADVANCE JAVA
Classified e-Material 48
URLConnection and HTTPURLConnection class
URLConnection
It is an abstract class.
It gives information about the web object,
connection to web object.
It provides the way to interact with the web object.
Example
URL url = new URL ("http://www.google.com/");
InputStream inputStream = url.openStream ();
OR
URL url = new URL ("http://www.google.com/");
URLConnection urlConnection = url.openConnection
();
InputStream inputStream = urlConnection.getInput
Stream ();
49. ADVANCE JAVA
Classified e-Material 49
URLConnection
The URL is constructed.
The URL’s openConnection() method creates the
URLConnection object.
The parameters for the connection and the
request properties that the client sends to the
server are set up.
The connect() method makes the connection to
the server. (optional)
The response header information is read using
getHeaderField().
50. ADVANCE JAVA
Classified e-Material 50
Header Viewer Example
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class MainClass {
public static void main(String args[]) throws Excep
tion {
URL u = new URL("http://www.java2s.com");
URLConnection uc = u.openConnection();
System.out.println("Content-
type: " + uc.getContentType());
System.out.println("Content-
encoding: " + uc.getContentEncoding());
System.out.println("Date: " + new Date(uc.getD
ate()));
51. ADVANCE JAVA
Classified e-Material 51
System.out.println("Last modified: " + new Date(uc.g
etLastModified()));
System.out.println("Expiration date: " + new Date(
uc.getExpiration()));
System.out.println("Content-
length: " + uc.getContentLength());
}}
Output:
Content-type: text/html
Content-encoding: null
Date: Thu May 24 18:41:00 PDT 2007
Last modified: Fri May 18 08:20:08 PDT 2007
Expiration date: Wed Dec 31 16:00:00 PST 1969
Content-length: 345648
52. ADVANCE JAVA
Classified e-Material 52
Writing to a Web server
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
public class MainClass {
public static void main(String[] a)throws Exception
{
URL url = new URL("http://www.yourdomain.com
/form.jsp");
URLConnection connection = url.openConnection()
;
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getO
utputStream());
out.println("firstName=Joe");
out.println("lastName=Average");
out.close();
}
}
56. ADVANCE JAVA
Classified e-Material 56
MIME
MIME is an acronym for "Multipurpose Internet
Mail Extensions".
An Internet standard defined in RFCs 2045
through 2049
Originally intended for use with email messages,
but has been been adopted for use in HTTP.
57. ADVANCE JAVA
Classified e-Material 57
Browser Request MIME Header
When the browser sends a request to a web
server, it also sends a MIME header.
MIME headers contain name-value pairs,
essentially a name followed by a colon and a
space, followed by a value.
Connection: Keep-Alive
User-Agent: Mozilla/3.01 (Macintosh; I; PPC)
Host: www.digitalthink.com:80
Accept: image/gif, image/x-xbitmap,
image/jpeg, image/pjpeg, */*
58. ADVANCE JAVA
Classified e-Material 58
Server Response MIME Header
When a web server responds to a web browser it
sends a response message and a MIME header
along with the response that looks something like
this:
HTTP/1.0 200 OK
Server: Netscape-Enterprise/2.01
Date: Sat, 02 Aug 1997 07:52:46 GMT
Accept-ranges: bytes
Last-modified: Tue, 29 Jul 1997 15:06:46 GMT
Content-length: 2810
Content-type: text/html