SlideShare a Scribd company logo
1 of 58
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

What's hot (20)

Java networking programs socket based
Java networking programs socket basedJava networking programs socket based
Java networking programs socket based
 
java networking
 java networking java networking
java networking
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
Networking in java
Networking in javaNetworking in java
Networking in java
 
Java Programming - 07 java networking
Java Programming - 07 java networkingJava Programming - 07 java networking
Java Programming - 07 java networking
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
Java- Datagram Socket class & Datagram Packet class
Java- Datagram Socket class  & Datagram Packet classJava- Datagram Socket class  & Datagram Packet class
Java- Datagram Socket class & Datagram Packet class
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Java sockets
Java socketsJava sockets
Java sockets
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Chap 1 Network Theory & Java Overview
Chap 1   Network Theory & Java OverviewChap 1   Network Theory & Java Overview
Chap 1 Network Theory & Java Overview
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 
28 networking
28  networking28  networking
28 networking
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 

Viewers also liked (15)

java code and document security
java code and document securityjava code and document security
java code and document security
 
Java Beans
Java BeansJava Beans
Java Beans
 
URL Class in JAVA
URL Class in JAVAURL Class in JAVA
URL Class in JAVA
 
Unit iv
Unit ivUnit iv
Unit iv
 
Beans presentation
Beans presentationBeans presentation
Beans presentation
 
Java beans
Java beansJava beans
Java beans
 
Santa Ana School.pptx
Santa Ana School.pptxSanta Ana School.pptx
Santa Ana School.pptx
 
Bean Intro
Bean IntroBean Intro
Bean Intro
 
javabeans
javabeansjavabeans
javabeans
 
introduction of Java beans
introduction of Java beansintroduction of Java beans
introduction of Java beans
 
java swing programming
java swing programming java swing programming
java swing programming
 
Java beans
Java beansJava beans
Java beans
 
Javabeans
JavabeansJavabeans
Javabeans
 
Java beans
Java beansJava beans
Java beans
 
Introduction to java beans
Introduction to java beansIntroduction to java beans
Introduction to java beans
 

Similar to Java Networking

Networking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in programNetworking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in programgovindjha339843
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket ProgrammingVipin Yadav
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13Sasi Kala
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Java client socket-20070327
Java client socket-20070327Java client socket-20070327
Java client socket-20070327Tsu-Fen Han
 
Javanetworkingbasicssocketsoverview
JavanetworkingbasicssocketsoverviewJavanetworkingbasicssocketsoverview
Javanetworkingbasicssocketsoverviewrajshreemuthiah
 
Java networking basics & sockets overview
Java networking basics & sockets overviewJava networking basics & sockets overview
Java networking basics & sockets overviewrajshreemuthiah
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxDhrumilSheth3
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project ReportKavita Sharma
 

Similar to Java Networking (20)

Networking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in programNetworking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in program
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
Java 1
Java 1Java 1
Java 1
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Java client socket-20070327
Java client socket-20070327Java client socket-20070327
Java client socket-20070327
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Sockets
SocketsSockets
Sockets
 
Network
NetworkNetwork
Network
 
Javanetworkingbasicssocketsoverview
JavanetworkingbasicssocketsoverviewJavanetworkingbasicssocketsoverview
Javanetworkingbasicssocketsoverview
 
Java networking basics & sockets overview
Java networking basics & sockets overviewJava networking basics & sockets overview
Java networking basics & sockets overview
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptx
 
Socket & Server Socket
Socket & Server SocketSocket & Server Socket
Socket & Server Socket
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Java networking
Java networkingJava networking
Java networking
 
A.java
A.javaA.java
A.java
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
 

More from Ankit Desai

java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transferAnkit Desai
 
Presentation14 audio play
Presentation14 audio playPresentation14 audio play
Presentation14 audio playAnkit Desai
 
Presentation15 parse xml
Presentation15 parse xmlPresentation15 parse xml
Presentation15 parse xmlAnkit Desai
 
Presentation11 sq lite
Presentation11 sq litePresentation11 sq lite
Presentation11 sq liteAnkit Desai
 
Hadoop installation
Hadoop installationHadoop installation
Hadoop installationAnkit Desai
 
Presentation10 view navigation
Presentation10 view navigationPresentation10 view navigation
Presentation10 view navigationAnkit Desai
 
Presentation7 segment control
Presentation7 segment controlPresentation7 segment control
Presentation7 segment controlAnkit Desai
 
Presentation6 ui image_view
Presentation6 ui image_viewPresentation6 ui image_view
Presentation6 ui image_viewAnkit Desai
 
Presentation5 picker view
Presentation5 picker viewPresentation5 picker view
Presentation5 picker viewAnkit Desai
 
Presentation4 date picker
Presentation4 date pickerPresentation4 date picker
Presentation4 date pickerAnkit Desai
 
Presentation3 actionsheet alertview
Presentation3 actionsheet alertviewPresentation3 actionsheet alertview
Presentation3 actionsheet alertviewAnkit Desai
 
Presentation1 password
Presentation1 passwordPresentation1 password
Presentation1 passwordAnkit Desai
 
Presentation2 gesture control
Presentation2 gesture controlPresentation2 gesture control
Presentation2 gesture controlAnkit Desai
 
Presentation8 silder switch_progress
Presentation8 silder switch_progressPresentation8 silder switch_progress
Presentation8 silder switch_progressAnkit Desai
 

More from Ankit Desai (17)

java Jdbc
java Jdbc java Jdbc
java Jdbc
 
java drag and drop and data transfer
java drag and drop and data transferjava drag and drop and data transfer
java drag and drop and data transfer
 
Java RMI
Java RMIJava RMI
Java RMI
 
JDBC
JDBCJDBC
JDBC
 
Presentation14 audio play
Presentation14 audio playPresentation14 audio play
Presentation14 audio play
 
Presentation15 parse xml
Presentation15 parse xmlPresentation15 parse xml
Presentation15 parse xml
 
Presentation11 sq lite
Presentation11 sq litePresentation11 sq lite
Presentation11 sq lite
 
Hadoop installation
Hadoop installationHadoop installation
Hadoop installation
 
Presentation10 view navigation
Presentation10 view navigationPresentation10 view navigation
Presentation10 view navigation
 
Presentation7 segment control
Presentation7 segment controlPresentation7 segment control
Presentation7 segment control
 
Presentation6 ui image_view
Presentation6 ui image_viewPresentation6 ui image_view
Presentation6 ui image_view
 
Presentation5 picker view
Presentation5 picker viewPresentation5 picker view
Presentation5 picker view
 
Presentation4 date picker
Presentation4 date pickerPresentation4 date picker
Presentation4 date picker
 
Presentation3 actionsheet alertview
Presentation3 actionsheet alertviewPresentation3 actionsheet alertview
Presentation3 actionsheet alertview
 
Presentation1 password
Presentation1 passwordPresentation1 password
Presentation1 password
 
Presentation2 gesture control
Presentation2 gesture controlPresentation2 gesture control
Presentation2 gesture control
 
Presentation8 silder switch_progress
Presentation8 silder switch_progressPresentation8 silder switch_progress
Presentation8 silder switch_progress
 

Recently uploaded

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

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