SlideShare a Scribd company logo
ADVANCE JAVA
ADVANCE JAVA
ADVANCE JAVA
Classified e-Material 2
NETWORK PROGRAMMING
java.net
PACKAGE
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
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
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.
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.
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.
ADVANCE JAVA
Classified e-Material 8
InetAddress Examples
try
{
InetAddress host = InetAddress.getLocalHost();
System.out.println(host.getHostName());
byte ip[] = host.getAddress();
for (int i=0; i<ip.length; i++) {
if (i > 0) {
System.out.print(".");
}
System.out.print(ip[i] & 0xff);
}
}
catch (UnknownHostException e)
{ // Exception handling here. }
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.
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()
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.
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.
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.
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
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.
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.
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)
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
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
ADVANCE JAVA
Classified e-Material 20
 public boolean getReuseAddress() throws
SocketException
 Tests if SO_REUSEADDR is enabled
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();
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.
}
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();
ADVANCE JAVA
Classified e-Material 24
TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
BufferedReader inFrom = new BufferedReader(new InputStreamReader(argv[0]));
Socket clientSock = new Socket("hostname", 6789);
DataOutputStream outTo = new DataOutputStream(clientSock.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFrom.readLine();
outToServer.writeBytes(sentence + 'n');
modifiedSentence = inFrom.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSock.close();
}
}
ADVANCE JAVA
Classified e-Material 25
TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + 'n';
outToClient.writeBytes(capitalizedSentence);
} } }
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
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);
}
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!
}
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.
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.
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.
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.
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.
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()));
ADVANCE JAVA
Classified e-Material 47
String line;
while ((line = inStream.readLine())!= null)
{ System.out.println(line); }
inStream.close();
}catch (MalformedURLException ex){ error("Bad
URL");
}catch (IOException ex){ error("IOException
occurred."); } }
public static void error(String s){
System.out.println(s);
System.exit(1);
}
}
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 ();
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().
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()));
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
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();
}
}
ADVANCE JAVA
Classified e-Material
©Copyrights Charotar Institute of 53
URLEncoder class
 Alphanumeric ASCII characters (a-z, A-Z, and 0-9)
and the $-_.!*'(), punctuation symbols are left
unchanged.
 The space character is converted into a plus sign
(+).
 Other characters (e.g. &, =, ^, #, %, ^, {, and so
on) are translated into a percent sign followed by
the two hexadecimal digits corresponding to their
numeric value.
 Example:
 The comma is ASCII character 44 (decimal) or 2C
(hex). Therefore if the comma appears as part of a
URL it is encoded as %2C.
 The query string "Author=Sadie, Julie&Title=Women
Composers" is encoded as: Author=Sadie
%2C+Julie&Title=Women+Composers
ADVANCE JAVA
Classified e-Material 54
URLEncoder methods
 URLEncoder.encode(String s)
 URLEncoder.decode(String s)
ADVANCE JAVA
Classified e-Material 55
 Example
 String qs = "Author=Sadie, Julie&Title=Women
Composers"; String eqs = URLEncoder.encode(qs);
System.out.println(eqs);
 Prints:
 Author%3dSadie%2c+Julie%26Title
%3dWomen+Composers
 String eqs = "Author=" +
URLEncoder.encode("Sadie, Julie");
 eqs += "&";
 eqs += "Title=";
 eqs += URLEncoder.encode("Women Composers");
 Prints:
 Author=Sadie%2c+Julie&Title=Women+Composers
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.
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, */*
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

More Related Content

What's hot (20)

PDF
Java networking programs socket based
Mukesh Tekwani
 
PPT
java networking
Waheed Warraich
 
PPTX
Networking in Java
Tushar B Kute
 
PPT
Networking in java
shravan kumar upadhayay
 
PDF
Java Programming - 07 java networking
Danairat Thanabodithammachari
 
PPTX
Java socket programming
Mohammed Abdalla Youssif
 
PPT
Networking Java Socket Programming
Mousmi Pawar
 
PPTX
Socket programming in Java (PPTX)
UC San Diego
 
PDF
Java- Datagram Socket class & Datagram Packet class
Ruchi Maurya
 
PPTX
Tcp/ip server sockets
rajshreemuthiah
 
PPT
Networking & Socket Programming In Java
Ankur Agrawal
 
PPT
Socket programming-tutorial-sk
sureshkarthick37
 
PDF
Java sockets
Stephen Pradeep
 
PPT
Socket Programming - nitish nagar
Nitish Nagar
 
PPTX
Java Networking
68SachinYadavSYCS
 
PDF
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
PPT
Network programming in Java
Tushar B Kute
 
PPTX
Java - Sockets
Riccardo Cardin
 
PDF
28 networking
Ravindra Rathore
 
PPT
Md13 networking
Rakesh Madugula
 
Java networking programs socket based
Mukesh Tekwani
 
java networking
Waheed Warraich
 
Networking in Java
Tushar B Kute
 
Networking in java
shravan kumar upadhayay
 
Java Programming - 07 java networking
Danairat Thanabodithammachari
 
Java socket programming
Mohammed Abdalla Youssif
 
Networking Java Socket Programming
Mousmi Pawar
 
Socket programming in Java (PPTX)
UC San Diego
 
Java- Datagram Socket class & Datagram Packet class
Ruchi Maurya
 
Tcp/ip server sockets
rajshreemuthiah
 
Networking & Socket Programming In Java
Ankur Agrawal
 
Socket programming-tutorial-sk
sureshkarthick37
 
Java sockets
Stephen Pradeep
 
Socket Programming - nitish nagar
Nitish Nagar
 
Java Networking
68SachinYadavSYCS
 
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
Network programming in Java
Tushar B Kute
 
Java - Sockets
Riccardo Cardin
 
28 networking
Ravindra Rathore
 
Md13 networking
Rakesh Madugula
 

Viewers also liked (15)

PPTX
java code and document security
Ankit Desai
 
PPTX
Java Beans
Ankit Desai
 
PPT
URL Class in JAVA
Ramasubbu .P
 
PPTX
Unit iv
bhushan_adavi
 
PPT
Beans presentation
manjusha ganesan
 
PPT
Java beans
Ramraj Choudhary
 
PPTX
Santa Ana School.pptx
sofiathoma
 
PPT
Bean Intro
vikram singh
 
PDF
javabeans
Arjun Shanka
 
PPT
introduction of Java beans
shravan kumar upadhayay
 
PPT
java swing programming
Ankit Desai
 
PDF
Java beans
Ravi Kant Sahu
 
PPTX
Javabeans
vamsitricks
 
PPT
Java beans
sptatslide
 
PPT
Introduction to java beans
Hitesh Parmar
 
java code and document security
Ankit Desai
 
Java Beans
Ankit Desai
 
URL Class in JAVA
Ramasubbu .P
 
Unit iv
bhushan_adavi
 
Beans presentation
manjusha ganesan
 
Java beans
Ramraj Choudhary
 
Santa Ana School.pptx
sofiathoma
 
Bean Intro
vikram singh
 
javabeans
Arjun Shanka
 
introduction of Java beans
shravan kumar upadhayay
 
java swing programming
Ankit Desai
 
Java beans
Ravi Kant Sahu
 
Javabeans
vamsitricks
 
Java beans
sptatslide
 
Introduction to java beans
Hitesh Parmar
 
Ad

Similar to Java Networking (20)

PPT
Networking.ppt(client/server, socket) uses in program
govindjha339843
 
PPT
Java Socket Programming
Vipin Yadav
 
PPT
Socket Programming it-slideshares.blogspot.com
phanleson
 
PPTX
Java 1
VidyaVarshini3
 
DOCX
Lab manual cn-2012-13
Sasi Kala
 
PPTX
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
KuntalVasoya
 
PPT
Pemrograman Jaringan
belajarkomputer
 
PPT
Socket programming
harsh_bca06
 
PPT
Socket programming
harsh_bca06
 
PPT
Java client socket-20070327
Tsu-Fen Han
 
PPT
Unit 8 Java
arnold 7490
 
PPT
Sockets
sivindia
 
PPT
Network
phanleson
 
PPTX
Java networking basics & sockets overview
rajshreemuthiah
 
PPTX
Javanetworkingbasicssocketsoverview
rajshreemuthiah
 
PPTX
CHAPTER - 3 - JAVA NETWORKING.pptx
DhrumilSheth3
 
PPTX
Socket & Server Socket
Hemant Chetwani
 
PPT
Socket Programming
Sivadon Chaisiri
 
PPT
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Abodahab
 
PPTX
Java networking
ssuser3a47cb
 
Networking.ppt(client/server, socket) uses in program
govindjha339843
 
Java Socket Programming
Vipin Yadav
 
Socket Programming it-slideshares.blogspot.com
phanleson
 
Lab manual cn-2012-13
Sasi Kala
 
Advanced Java Programming: Introduction and Overview of Java Networking 1. In...
KuntalVasoya
 
Pemrograman Jaringan
belajarkomputer
 
Socket programming
harsh_bca06
 
Socket programming
harsh_bca06
 
Java client socket-20070327
Tsu-Fen Han
 
Unit 8 Java
arnold 7490
 
Sockets
sivindia
 
Network
phanleson
 
Java networking basics & sockets overview
rajshreemuthiah
 
Javanetworkingbasicssocketsoverview
rajshreemuthiah
 
CHAPTER - 3 - JAVA NETWORKING.pptx
DhrumilSheth3
 
Socket & Server Socket
Hemant Chetwani
 
Socket Programming
Sivadon Chaisiri
 
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Abodahab
 
Java networking
ssuser3a47cb
 
Ad

More from Ankit Desai (17)

PPTX
java Jdbc
Ankit Desai
 
PPTX
java drag and drop and data transfer
Ankit Desai
 
PPTX
Java RMI
Ankit Desai
 
PPT
JDBC
Ankit Desai
 
PPTX
Presentation14 audio play
Ankit Desai
 
PPTX
Presentation15 parse xml
Ankit Desai
 
PPTX
Presentation11 sq lite
Ankit Desai
 
PPTX
Hadoop installation
Ankit Desai
 
PPTX
Presentation10 view navigation
Ankit Desai
 
PPTX
Presentation7 segment control
Ankit Desai
 
PPTX
Presentation6 ui image_view
Ankit Desai
 
PPTX
Presentation5 picker view
Ankit Desai
 
PPTX
Presentation4 date picker
Ankit Desai
 
PPTX
Presentation3 actionsheet alertview
Ankit Desai
 
PPTX
Presentation1 password
Ankit Desai
 
PPTX
Presentation2 gesture control
Ankit Desai
 
PPTX
Presentation8 silder switch_progress
Ankit Desai
 
java Jdbc
Ankit Desai
 
java drag and drop and data transfer
Ankit Desai
 
Java RMI
Ankit Desai
 
Presentation14 audio play
Ankit Desai
 
Presentation15 parse xml
Ankit Desai
 
Presentation11 sq lite
Ankit Desai
 
Hadoop installation
Ankit Desai
 
Presentation10 view navigation
Ankit Desai
 
Presentation7 segment control
Ankit Desai
 
Presentation6 ui image_view
Ankit Desai
 
Presentation5 picker view
Ankit Desai
 
Presentation4 date picker
Ankit Desai
 
Presentation3 actionsheet alertview
Ankit Desai
 
Presentation1 password
Ankit Desai
 
Presentation2 gesture control
Ankit Desai
 
Presentation8 silder switch_progress
Ankit Desai
 

Recently uploaded (20)

PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PPTX
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Python basic programing language for automation
DanialHabibi2
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
SFWelly Summer 25 Release Highlights July 2025
Anna Loughnan Colquhoun
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
July Patch Tuesday
Ivanti
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
MSP360 Backup Scheduling and Retention Best Practices.pptx
MSP360
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 

Java Networking

  • 2. ADVANCE JAVA Classified e-Material 2 NETWORK PROGRAMMING java.net PACKAGE
  • 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.
  • 8. ADVANCE JAVA Classified e-Material 8 InetAddress Examples try { InetAddress host = InetAddress.getLocalHost(); System.out.println(host.getHostName()); byte ip[] = host.getAddress(); for (int i=0; i<ip.length; i++) { if (i > 0) { System.out.print("."); } System.out.print(ip[i] & 0xff); } } catch (UnknownHostException e) { // Exception handling here. }
  • 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
  • 20. ADVANCE JAVA Classified e-Material 20  public boolean getReuseAddress() throws SocketException  Tests if SO_REUSEADDR is enabled
  • 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();
  • 24. ADVANCE JAVA Classified e-Material 24 TCPClient.java import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFrom = new BufferedReader(new InputStreamReader(argv[0])); Socket clientSock = new Socket("hostname", 6789); DataOutputStream outTo = new DataOutputStream(clientSock.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFrom.readLine(); outToServer.writeBytes(sentence + 'n'); modifiedSentence = inFrom.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSock.close(); } }
  • 25. ADVANCE JAVA Classified e-Material 25 TCPServer.java import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + 'n'; outToClient.writeBytes(capitalizedSentence); } } }
  • 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()));
  • 47. ADVANCE JAVA Classified e-Material 47 String line; while ((line = inStream.readLine())!= null) { System.out.println(line); } inStream.close(); }catch (MalformedURLException ex){ error("Bad URL"); }catch (IOException ex){ error("IOException occurred."); } } public static void error(String s){ System.out.println(s); System.exit(1); } }
  • 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(); } }
  • 53. ADVANCE JAVA Classified e-Material ©Copyrights Charotar Institute of 53 URLEncoder class  Alphanumeric ASCII characters (a-z, A-Z, and 0-9) and the $-_.!*'(), punctuation symbols are left unchanged.  The space character is converted into a plus sign (+).  Other characters (e.g. &, =, ^, #, %, ^, {, and so on) are translated into a percent sign followed by the two hexadecimal digits corresponding to their numeric value.  Example:  The comma is ASCII character 44 (decimal) or 2C (hex). Therefore if the comma appears as part of a URL it is encoded as %2C.  The query string "Author=Sadie, Julie&Title=Women Composers" is encoded as: Author=Sadie %2C+Julie&Title=Women+Composers
  • 54. ADVANCE JAVA Classified e-Material 54 URLEncoder methods  URLEncoder.encode(String s)  URLEncoder.decode(String s)
  • 55. ADVANCE JAVA Classified e-Material 55  Example  String qs = "Author=Sadie, Julie&Title=Women Composers"; String eqs = URLEncoder.encode(qs); System.out.println(eqs);  Prints:  Author%3dSadie%2c+Julie%26Title %3dWomen+Composers  String eqs = "Author=" + URLEncoder.encode("Sadie, Julie");  eqs += "&";  eqs += "Title=";  eqs += URLEncoder.encode("Women Composers");  Prints:  Author=Sadie%2c+Julie&Title=Women+Composers
  • 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