Chapter 4 (Java Networking)
Chapter 4 (Java Networking)
JAVA NETWORKING
By: Behayilu M.
Faculty of Computing and software Eng.(FCSE),
Arba Minch Institute of Technology(AMiT),
Arba Minch University
Objectives
Port is an optional parameter. If a port is not specified, the default port for the protocol
is used. With HTTP, the default port is 80.
The path is also referred to as the filename,.
E.g: http://www.amrood.com/index.htm?language=en#j2se
URL class methods
The java.net.URL class represents a URL and has complete set of methods to manipulate
URL in Java.
The URL class has several constructors for creating URLs, including the following:
public URL(String protocol, String host, int port, Creates a URL by putting together the given
String file) throws MalformedURLException parts.
public URL(String protocol, String host,String Identical to the previous constructor, except that
file) throws MalformedURLException the default port for the given protocol is used.
public URL(URL context, String url) Creates a URL by parsing the together the URL
throws MalformedURLException and String arguments
…cont’d
The URL class contains many methods for accessing the various parts of the URL being
represented. Some of the methods in the URL class include the following:
public String getPath() Returns the path of the URL
public String getQuery() Returns the query part of the URL.
public String getAuthority() Returns the authority of the URL
public int getPort() Returns the port of the URL
public int getDefaultPort() Returns the default port for the protocol
of the URL.
public String getProtocol() Returns the protocol of the URL.
public String getHost() Returns the host of the URL.
public String getFile() Returns the filename of the URL.
public String getRef() Returns the reference part of the URL
public URLConnection openConnection() Opens a connection to the URL,
throws IOException allowing a client to communicate with
the resource
import java.net.*; …cont’d
import java.io.*;
public class URLTest{
public static void main(String args[])
{
try{
URL url=new URL("http://www.amrood.com/index.htm ?language=en#j2se");
System.out.println("URL is "+ url.toString());
System.out.println("protocol is "+ url.getProtocol());
URL is http://www.amrood.com/index.htm?language=en#j2se
System.out.println("authority is "+ url.getAuthority());
protocol is http
System.out.println("file name is "+ url.getFile());
authority is www.amrood.com
System.out.println("host is "+ url.getHost());
file name is /index.htm?language=en
System.out.println("path is "+ url.getPath());
host is www.amrood.com
System.out.println("port is "+ url.getPort());
path is /index.htm
System.out.println("default port is "+ url.getDefaultPort()); port is -1
System.out.println("query is "+ url.getQuery()); default port is 80
System.out.println("ref is "+ url.getRef()); query is language=en
}catch(IOException e){e.printStackTrace(); ref is j2se
}}
}
URLConnection class
URLConnection is a general-purpose class for accessing the attributes of a remote resource.
Once we make a connection to a remote server, we can use URLConnection to inspect the properties
of the remote object before actually transporting it locally.
URLConnection is created using the openConnection( ) method of a URL object and can then use it
to examine the document’s properties and content.
For example: If you connect to a URL whose protocol is HTTP, the openConnection() method returns
an HttpURLConnection object.
If you connect to a URL that represents a JAR file, the openConnection() method returns a
JarURLConnection object. etc...
…cont’d
The URLConnection class has many methods for setting or determining information about
the connection, including the following:
Object getContent() Retrieves the contents of this URL connection.
public InputStream Returns the input stream of the URL connection for reading from the
getInputStream() throws resource.
IOException
public OutputStream Returns the output stream of the URL connection for writing to the
getOutputStream() throws resource
IOException
public URL getURL() Returns the URL that this URLConnection object is connected to
…cont’d
import java.io.*;
public class URLConnectionReader
{
public static void main(String[] args) throws Exception
{
URL ur = new URL("http://www.amu.edu.et");
URLConnection uc = ur.openConnection();
System.out.println("Content Type: " + uc.getContentType());
BufferedReader in = new BufferedReader(new
InputStreamReader(uc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
The InetAdress class
Handles Internet addresses both as host names and as IP addresses.
Static method getByName of this class uses DNS (Domain Name System) to return the
Internet address of a specified host name as an InetAddress object.
In order to display the IP address from this object, we can simply use method println().
(which will cause the object's toString() method to be executed).
{
System.out.println("Could not find " + host);
}
}}
Socket programming
Java Socket programming is used for communication between the applications running on different
JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming.
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Java socket programming provides facility to share data between different computing
devices.
OutputStream InputStream
Send and receive data using streams
Server
Client
InputStream OutputStream 7
Socket programming
Socket is an abstraction that is provided to an application programmer to send or
receive data to another process.
Data can be sent to or received from another process running on the same machine or
a different machine.
It is used to indicate one of the two end-points of a communication link between two
processes.
TCP/IP Socket programming
• Java provides the ServerSocket class for creating a server socket and the Socket class for creating a client
socket.
• Two programs on the Internet communicate through a server socket and a client socket using I/O streams.
• Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data.
• Once a connection is established, the client and the server communicate through sockets.
• The server must be running when a client attempts to connect to the server.
20
Server Sockets
To establish a server, you need to create a server socket and attach it to a port,
which is where the server listens for connections.
The port identifies the TCP service on the socket.
The following statement creates a server socket serverSocket:
ServerSocket serverSocket = new ServerSocket(port);
Attempting to create a server socket on a port already in use would cause the
java.net.BindException.
21
Client Sockets
After a server socket is created, the server can use the following
statement to listen for connections:
This statement opens a socket so that the client program can communicate
22
with
Client Sockets
serverName is the server’s Internet host name or IP address.
The following statement creates a socket on the client machine to connect to the host
130.254.204.33 at port 8000:
Alternatively, you can use the domain name to create a socket, as follows:
• After the server accepts the connection, communication between the server and
• The statements needed to create the streams and to exchange data between them
24
Data Transmission through Sockets
25
Data Transmission through Sockets
To get an input stream and an output stream, use the getInputStream() and
getOutputStream() methods on a socket object.
For example, the following statements create an InputStream stream called
input and an OutputStream stream called output from a socket:
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
• You can use DataInputStream, DataOutputStream and BufferedReader to wrap on the InputStream
and OutputStream to read or write data, such as int, double, or String.
• The following statements, for instance, create the DataInputStream stream input and the
DataOutputStream stream output to read and write primitive data values:
DataInputStream input = new DataInputStream (socket.getInputStream());
DataOutputStream output = new DataOutputStream (socket.getOutputStream());
• The server can use input.readDouble() to receive a double value from the client, and
output.writeDouble(d) to send the double value d to the client.
• Binary I/O is more efficient than text I/O because text I/O requires encoding and decoding.
• Therefore, it is better to use binary I/O for transmitting data between a server and a client to improve
27
performance.
Example…one way communication
import java.net.*;
import java.io.*;
public class SimpleServer{
public static void main(String args[]) throws IOException
{
ServerSocket ss=new ServerSocket(2223);
Socket s=ss.accept();
OutputStream sout=s.getOutputStream();
DataOutputStream dos=new DataOutputStream(sout);
dos.writeUTF("Hi I am Server");
dos.close();
sout.close();
s.close();
}
}
Example…one way communication
import java.net.*;
import java.io.*;
public class SimpleClient{
public static void main(String args[]) throws IOException
{
Socket s=new Socket("localhost",2223);
InputStream sin=s.getInputStream();
DataInputStream dis=new DataInputStream(sin);
String str=new String(dis.readUTF());
System.out.println(str);
dis.close();
sin.close();
s.close();
}
}
Exercise
• Problem: Write a client and a server program that the client sends data to a server.
The server receives the data, uses it to produce a result, and then sends the result
back to the client. The client displays the result on the console. In this example, the
data sent from the client is the radius of a circle, and the result produced by the
server is the area of the circle. The client sends the radius to the server; the server
computes the area and sends it to the client.
compute area
radius
Server Client
area
30
UDP Socket Programming
Datagram packets are used to implement a connectionless packet delivery service
supported by the UDP protocol.
That means, each packet might be routed differently, and might arrive in any order.
DatagramPacket
DatagramSocket
UDP Socket Programming
A datagram socket is the sending or receiving point for a packet delivery service.
Each message is routed from one machine to based solely on information contained
within that packet.
UDP Socket Programming
The class DatagramSocket contains several constructors that can be used for
creating socket.
This constructor is used for creating a datagram packet for sending packets of
length ‘length’ to the specified port number on the specified host.
int getLength() Returns the length of the data to be sent or the length of the
data received
void setData(byte[] buf) Sets the data buffer for this packet.