Network-Programming in Java
Network-Programming in Java
Basics of networking
UDP
○ 1024-49151
■ These are called user or registered ports
■ Can be registered by companies and developers for a
particular service
■ Ex: 1102 (Adobe server), 1527 (Oracle server)
○ 49152-65536
■ These are called dynamic or private ports
■ These are client-side port that are free to use
■ These are the ports that our computer assigns temporarily to
itself during a session
■ Ex: viewing a webpage
● By using the package java.net, java programs can use TCP or UDP to
communicate over the internet
● URL, URLConnection, Socket, ServerSocket classes all use TCP to
communicate over the internet
● DatagramPacket, DatagramSocket, MulticastSocket classes are used for
UDP
Working with URLs
URL
For many protocols, the host name and the filename are required, while the port
number and reference are optional.
Complete URL :
http://www.example.com:8080/path/to/resource/file.html#section2
Creating a URL
● The easiest way to create a URL object is from a String that represents the
human-readable form of the URL address.
● In your Java program, you can use a String containing this text to create a
URL object:
URL myURL = new URL("http://example.com/");
● The URL object created above represents an absolute URL.
● You can also create URL objects from a relative URL address.
● In your Java programs, you can create a URL object from a relative URL
specification. For example, suppose you know two URLs at the site
example.com:
http://example.com/pages/page1.html
http://example.com/pages/page2.html
● You can create URL objects for these pages relative to their common base
URL:
http://example.com/pages/ like this:
URL myURL = new URL("http://example.com/pages/");
URL page1URL = new URL(myURL, "page1.html");
URL page2URL = new URL(myURL, "page2.html");
● This code snippet uses the URL constructor that lets you create a URL
object from another URL object (the base) and a relative URL specification.
● The general form of this constructor is:
URL(URL baseURL, String relativeURL)
● The first argument is a URL object that specifies the base of the new URL.
The second argument is a String that specifies the rest of the resource
name relative to the base.
● If baseURL is null, then this constructor treats relativeURL like an absolute
URL specification.
● Conversely, if relativeURL is an absolute URL specification, then the
constructor ignores baseURL.
● Other URL constructors:
new URL("http", "example.com", "/pages/page1.html");
○ This is equivalent to
new URL("http://example.com/pages/page1.html");
○ The first argument is the protocol, the second is the host name, and
the last is the pathname of the file.
○ Note that the filename contains a forward slash at the beginning.
This indicates that the filename is specified from the root of the host.
○ The final URL constructor adds the port number to the list of
arguments used in the previous constructor:
URL url = new URL("http", "example.com", 80,
"pages/page1.html");
○ This creates a URL object for the following URL:
http://example.com:80/pages/page1.html
○ If you construct a URL object using one of these constructors, you
can get a String containing the complete URL address by using the
URL object's toString method
● Some URL addresses contain special characters, for example the space
character. Like this:
http://example.com/hello world/
● To make these characters legal they need to be encoded before passing
them to the URL constructor.
URL url = new URL("http://example.com/hello%20world");
● Encoding the special character(s) in this example is easy as there is only
one character that needs encoding,
● But for URL addresses that have several of these characters or if you are
unsure when writing your code what URL addresses you will need to
access, you can use the multi-argument constructors of the java.net.URI
class to automatically take care of the encoding for you.
URI uri = new URI("http", "example.com", "/hello world/", "");
● And then convert the URI to a URL.
URL url = uri.toURL();
Malformed URL
Parsing a URL
● The URL class provides several methods that let you query URL objects.
You can get the protocol, authority, host name, port number, path, query,
filename, and reference from a URL using these accessor methods:
getProtocol
Returns the protocol identifier component of the URL.
Example : http
getAuthority
Returns the authority component of the URL.
Example : user:[email protected]:8080
getHost
Returns the host name component of the URL.
Example : www.example.com
getPort
Returns the port number component of the URL. The getPort method
returns an integer that is the port number. If the port is not set, getPort
returns -1.
Example : 8080
getPath
Returns the path component of this URL.
Example : /path/to/resource/file.html
getQuery
Returns the query component of this URL.
Example : param1=value¶m2=value
getFile
Returns the filename component of the URL. The getFile method returns
the same as getPath, plus the concatenation of the value of getQuery, if
any.
Example : /path/to/resource/file.html?param1=value1¶m2=value2
getRef
Returns the reference component of the URL.
Example : section2
● Note:
Remember that not all URL addresses contain these components. The
URL class provides these methods because HTTP URLs do contain these
components and are perhaps the most commonly used URLs.
● The URL class is somewhat HTTP-centric.
● You can use these getXXX methods to get information about the URL
regardless of the constructor that you used to create the URL object.
● The URL class, along with these accessor methods, frees you from ever
having to parse URLs again!
● Given any string specification of a URL, just create a new URL object and
call any of the accessor methods for the information you need.
● This small example program creates a URL from a string specification and
then uses the URL object's accessor methods to parse the URL:
Output:
● After you've successfully created a URL, you can call the URL's
openStream() method to get a stream from which you can read the
contents of the URL.
● The openStream() method returns a java.io.InputStream object, so reading
from a URL is as easy as reading from an input stream.
● The following small Java program uses openStream() to get an input
stream on the URL
http://www.google.com.np/
● It then opens a BufferedReader on the input stream and reads from the
BufferedReader thereby reading from the URL.
● Everything read is copied to the standard output stream
● Example :
Connecting to a URL
● After you've successfully created a URL object, you can call the URL
object's openConnection method to get a URLConnection object, or one of
its protocol specific subclasses, e.g. java.net.HttpURLConnection
● You can use this URLConnection object to setup parameters and general
request properties that you may need before connecting.
● Connection to the remote object represented by the URL is only initiated
when the URLConnection.connect method is called.
● When you do this you are initializing a communication link between your
Java program and the URL over the network.
● For example, the following code opens a connection to the site
example.com:
● A new URLConnection object is created every time by calling the
openConnection method of the protocol handler for this URL.
● You are not always required to explicitly call the connect method to initiate
the connection.
● Operations that depend on being connected, like getInputStream,
getOutputStream, etc, will implicitly perform the connection, if necessary.
● Now that you've successfully connected to your URL, you can use the
URLConnection object to perform actions such as reading from or writing
to the connection. The next example shows how.
What is socket?
The java.net package in the Java platform provides a class, Socket, that
implements one side of a two-way connection between your Java program and
another program on the network.
On the client-side: The client knows the hostname of the machine on which the
server is running and the port number on which the server is listening. To make a
connection request, the client tries to connect with the server on the server's
machine and port. The client also needs to identify itself to the server, so it binds
to a local port number that it will use during this connection. This is usually
assigned by the system.
If everything goes well, the server accepts the connection. Upon acceptance, the
server gets a new socket bound to the same local port and also has its remote
endpoint set to the address and port of the client.
The client and server can now communicate by writing to or reading from their
sockets.
● Step 3 is to get the OutputStream and InputStream objects that enable the
server to communicate with the client by sending and receiving bytes
● The server invokes method getOutputStream on the Socket to get a
reference to the Socket’s OutputStream and invokes method
getInputStream on the Socket to get a reference to the Socket’s
InputStream
● The server and the client communicate via the OutputStream and
InputStream objects.
● In this phase the client and the server communicate via the InputStream
and OutputStream objects.
● It returns an InetAddress object that encapsulates the sequence of four bytes such as
132.163.4.104
● Sometimes host name corresponds to three different Internet addresses like
java.sun.com
● You can get all hosts with the getAllByName method
A client program
A server socket program
Serving Multiple Clients
● Clients from all over the internet may use server at the same time
● In normal client-server program as we have seen before, single client is
connected for long time and other clients are rejected
● This can be improved using threads
● How?
○ Whenever accept() is success, we launch a new thread
○ New thread will take care of connection between client and server
○ Now main program will go back and wait for next connection
● Now the main program will look like this:
while (true)
{
Socket incoming = s.accept();
Runnable r = new ThreadedEchoHandler(incoming);
Thread t = new Thread(r);
t.start();
}
● Because each connection starts a new thread, multiple clients can connect to the server
at the same time.
Socket Timeouts
● Used to limit the amount of time socket operation can take place
● To prevent from socket waiting indefinitely for connection, we can set the
timeout
try {
Socket clientSocket = serverSocket.accept();
// Handle the accepted connection
} catch (SocketTimeoutException e) {
Interruptible Sockets
● When you connect to a socket, the current thread blocks until the
connection has been established or a timeout has elapsed.
● Similarly, when you read or write data through a socket, the current thread
blocks until the operation is successful or has timed out.
● We cannot simply unblock it by calling the interrupt
● To interrupt a socket operation, you use a SocketChannel, a feature of the
java.nio package:
● Similarly, to turn a channel into an output stream,we can use the static
Channels.newOutputStream method.
OutputStream outStream = Channels.newOutputStream(channel);
● Whenever a thread is interrupted during an open, read, or write operation,
the operation does not block but is terminated with an exception.
Half-Close
First, you need to include two jar files into your CLASSPATH:
● mail.jar
● Activation.jar
After including jar files, you can start sending emails. However, you
need an SMTP server to send emails using JavaMail API. You can
easily set up an SMTP server using a provider like Mailtrap.
As the second step, you need to get the session object. The session
object contains all the information related to the host like name, user
name, password, etc. For that, you can write code like below.
// properties object contains host information
Properties properties = new Properties();
Session session=Session.getInstance(properties,null);
Also, you can pass the username and the password to obtain
authentication for a network connection.
Finally, you can use the javax.mail.Transport class to send the email.
Transport.send(message);
The complete code example of sending an email using JavaMail APi will look
like below: