1
NETWORK
Java - Networking
The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.
The java.net package provides support for the two common network protocols −
■ TCP − TCP stands for Transmission Control Protocol, which allows for
reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
■ UDP − UDP stands for User Datagram Protocol, a connection-less protocol
Socket Programming
■ Sockets provide the communication mechanism between two
computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.
■ When the connection is made, the server creates a socket
object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket.
■ The java.net.Socket class represents a socket, and the
java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them
The following steps occur when establishing a TCP connection between two computers using sockets −
■ The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
■ The server invokes the accept() method of the ServerSocket class. This method
waits until a client connects to the server on the given port.
■ After the server is waiting, a client instantiates a Socket object, specifying the
server name and the port number to connect to.
■ The constructor of the Socket class attempts to connect the client to the specified
server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server.
■ On the server side, the accept() method returns a reference to a new socket on the
server that is connected to the client's socket.
After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.
ServerSocket Class Methods
■ The java.net.ServerSocket class is used by server applications to obtain a port and listen for
client requests.
■ The ServerSocket class has four constructors −
5
If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and is ready for client requests.
■ Following are some of the common methods of the ServerSocket class −
Socket Class Methods
7
■ The java.net.Socket class represents the socket that both the client and the server use to communicate with
each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.
■ The Socket class has five constructors that a client uses to connect to a server −
When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port.
Java Networking
■
Java Networking is a concept of connecting two or
more computing devices together so that we can share
resources.
■
Java socket programming provides facility to share
data between different computing devices.
Advantage of Java Networking
■
sharing resources
■
centralize software management
Java Networking Terminology
The widely used java networking terminologies are
given below:
■
IP Address
■Protocol
■
Port Number
■MAC Address
■
Connection-oriented and connection-less protocol
■Socket
1) IP Address
■
IP address is a unique number assigned to a node
of a network e.g. 192.168.0.1 . It is composed of
octets that range from 0 to 255.
■
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed
for communication. For example:
■
TCP
■
FTP
■
Telnet
■
SMTP
3) Port Number
■
The port number is used to uniquely identify
different applications. It acts as a communication
endpoint between applications.
■
The port number is associated with the IP address
for communication between two applications.
4) MAC Address
MAC (Media Access Control) Address is a
unique identifier of NIC (Network Interface
Controller). A network node can have multiple
NIC but each with unique MAC.
5) Connection-oriented and
connection-less protocol
■
In connection-oriented protocol, acknowledgement is
sent by the receiver. So it is reliable but slow. The
example of connection-oriented protocol is TCP.
■
But, in connection-less protocol, acknowledgement is
not sent by the receiver. So it is not reliable but fast.
The example of connection-less protocol is UDP.
6) Socket
■
A socket is an endpoint between two way
Java Socket Programming
■ Java Socket programming is used for communication between
the applications running on different JRE.
■ Java Socket programming can be connection-oriented or
connection-less.
■ Socket and ServerSocket classes are used for
connection-oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
■ The client in socket programming must know two information:
■ IP Address of Server, and
■ Port number.
■
■ Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket.
ServerSocket class
19
■ The ServerSocket class can be used to create a server socket.
This object is used to establish communication with the clients.
Steps of Socket programming
■
Create Socket (server & client side)
■Listen the Socket
■
Read & write data on stream in socket
■Close the socket and stream
■
Creating A Socket
■
For client:
Socket MyClient;MyClient = new Socket("Machine name", PortNumber);
■ Where Machine name is the machine you are trying to
open a connection to, and PortNumber is the port (a
number) on which the server you are trying to connect to is running.
■ When selecting a port number, you should note that port
numbers between 0 and 1,023 are reserved for
privileged users (that is, super user or root). These port numbers are reserved for standard services, such as
email, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1,023!
Client with exception handling
■ Socket MyClient;
■ try
■ {
■ MyClient = new Socket("Machine name", PortNumber);
■ }
■ catch (IOException e)
■
For the Server:
■ ServerSocket MyService;
■ try
■ {
■ MyService = new ServerSocket(PortNumber);
■ }
■ catch (IOException e)
■ { System.out.println(e); }
Listining the Socket
■ When implementing a server you also need to create a
socket object from the ServerSocket in order to listen for and accept connections from clients.
■ Socket clientSocket = null;
■ Try ■ { ■ serviceSocket = MyService.accept(); ■ } ■ catch (IOException e) ■ { System.out.println(e); }
■ Taking Input & Output from Socket
■ In the client side, you can use the DataInputStream class to create
an input stream to receive response from the server:
DataInputStream input;
try {
input = new DataInputStream(MyClient.getInputStream()); }
catch (IOException e)
{ System.out.println(e); }
■ The class DataInputStream allows you to read lines of text and Java
primitive data types in a portable way.
■ It has methods such
as read, readChar, readInt,readDouble, and readLine,.
■ On the server side, you can use DataInputStream to receive input from the client:
DataInputStream input try
{
input = new DataInputStream(serviceSocket.getInputStream()); } catch (IOException e)
{
System.out.println(e);
■ On the client side, you can create an output stream to send information to the server socket using the
class PrintStream or DataOutputStream of java.io: PrintStream output;
try {
output = new PrintStream(MyClient.getOutputStream()); }
catch (IOException e)
{
System.out.println(e); }
■ The class PrintStream has methods for displaying textual
representation of Java primitive data types. Its Write and println methods are important here
■ Also, you may want to use the DataOutputStream:
DataOutputStream output;
try {
output = new DataOutputStream(MyClient.getOutputStream()); }
catch (IOException e)
{ System.out.println(e); }
■ The class DataOutputStream allows you to write Java
primitive data types; many of its methods write a single Java primitive type to the output stream. The
Close the socket
■ You should always close the output and input stream
before you close the socket.
■ On the client side:
try { output.close(); input.close(); MyClient.close(); } catch (IOException e) { System.out.println(e); } 29
■ On the server side: try { output.close(); input.close(); serviceSocket.close(); MyService.close(); } catch (IOException e) { System.out.println(e); }
Example of Java Socket Programming
File: MyServer.java
31
Let's see a simple of java socket programming in which client sends a text and server receives it .
■ import java.io.*;
■ import java.net.*;
■ public class MyServer {
■ public static void main(String[] args){
■ try{
■ ServerSocket ss=new ServerSocket(6666); ■ Socket s=ss.accept();//establishes connection
■ DataInputStream dis=new DataInputStream(s.getInputStream()); ■ String str=(String)dis.readUTF(); ■ System.out.println("message= "+str); ■ ss.close(); ■ }catch(Exception e){System.out.println(e);} ■ } ■ }
File: MyClient.java
■ import java.io.*; ■ import java.net.*;
■ public class MyClient {
■ public static void main(String[] args) { ■ try{
■ Socket s=new Socket("localhost",6666); ■ DataOutputStream dout=new DataOutputStre
am(s.getOutputStream()); ■ dout.writeUTF("Hello Server"); ■ dout.flush(); ■ dout.close(); ■ s.close(); ■ }catch(Exception e){System.out.println(e);} ■ } ■ }
Let's see a simple of java socket programming in which client sends a text and server receives it .
import java.io.*; import java.net.*;
public class MyServer {
public static void main(String[] args){ try{
ServerSocket ss=new ServerSocket(6666); Socket s=ss.accept();//establishes connection DataInputStream dis=new DataInputStream(s.ge tInputStream()); String str=(String)dis.readUTF(); System.out.println("message= "+str); ss.close(); }catch(Exception e){System.out.println(e);} } }
Output
To execute this program open two command prompts and execute each program at each command prompt as displayed in the below figure.
Example of Java Socket Programming (Read-Write both side)
import java.net.*; import java.io.*; class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333); Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream()); DataOutputStream dout=new DataOutputStream(s.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(System.i
n)); String str="",str2=""; while(!str.equals("stop")){ str=din.readUTF(); System.out.println("client says: "+str); str2=br.readLine(); dout.writeUTF(str2); dout.flush(); } din.close(); s.close(); ss.close(); }} import java.net.*; import java.io.*; class MyClient{
public static void main(String args[])throws Exceptio n{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInput Stream());
DataOutputStream dout=new DataOutputStream(s.get OutputStream());
BufferedReader br=new BufferedReader(new InputStr eamReader(System.in)); String str="",str2=""; while(!str.equals("stop")){ str=br.readLine(); dout.writeUTF(str); dout.flush(); str2=din.readUTF(); System.out.println("Server says: "+str2); } dout.close(); s.close();
File: MyClient.java
■ import java.net.*; ■ import java.io.*; ■ class MyClient{
■ public static void main(String args[])throws Exception{
■ Socket s=new Socket("localhost",3333);
■ DataInputStream din=new DataInputStream(s.getInputStream());
■ DataOutputStream dout=new DataOutputStream(s.getOutputStream());
■ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); ■ ■ String str="",str2=""; ■ while(!str.equals("stop")){ ■ str=br.readLine(); ■ dout.writeUTF(str); ■ dout.flush(); ■ str2=din.readUTF(); ■ System.out.println("Server says: "+str2); ■ } ■ ■ dout.close(); ■ s.close(); ■ }} 35
Socket Types
There are two widely used socket types, stream sockets, and datagram sockets.
■ Stream sockets treat communications as a continuous stream
of characters, while datagram sockets have to read entire messages at once. Each uses its own communications protocol. Stream sockets use TCP (Transmission Control Protocol), which is a reliable, stream oriented protocol.
■ Datagram sockets use UDP (Unix Datagram Protocol), which
is unreliable and message oriented. A second type of connection is a datagram socket. You might want to use a datagram socket in cases where there is only one message being sent from the client to the server, and only one message
Difference between Stream socket and Datagram socket
There are several differences between a datagram socket and a stream socket.
■ Datagrams are unreliable, which means that if a packet of information gets lost
somewhere in the Internet, the sender is not told (and of course the receiver does not know about the existence of the message). In contrast, with a stream socket, the underlying TCP protocol will detect that a message was lost because it was not acknowledged, and it will be retransmitted without the process at either end knowing about this.
■ Message boundaries are preserved in datagram sockets. If the sender sends a
datagram of 100 bytes, the receiver must read all 100 bytes at once. This can be contrasted with a stream socket, where if the sender wrote a 100 byte message, the receiver could read it in two chunks of 50 bytes or 100 chunks of one byte.
■ The communication is done using special system
calls sendto() andreceivefrom() rather than the more generic read() and write().
■ There is a lot less overhead associated with a datagram socket because connections
do not need to be established and broken down, and packets do not need to be acknowledged. This is why datagram sockets are often used when the service to be provided is short, such as a time-of-day service.
Java DatagramSocket and
DatagramPacket
Java DatagramSocket and DatagramPacket
classes are used for connection-less socket
programming
Java DatagramSocket class
Java DatagramSocket class represents a connection-less socket for
sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class
■ DatagramSocket() throws SocketEeption: it creates a datagram socket
and binds it with the available Port Number on the localhost machine.
■ DatagramSocket(int port) throws SocketEeption: it creates a datagram
socket and binds it with the given Port Number.
■ DatagramSocket(int port, InetAddress address) throws
SocketEeption: it creates a datagram socket and binds it with the specified
port number and host address.
Java DatagramPacket class
Java DatagramPacket is a message that can be sent or
received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
■ DatagramPacket(byte[] barr, int length): it creates a
datagram packet. This constructor is used to receive the packets.
■ DatagramPacket(byte[] barr, int length, InetAddress
address, int port): it creates a datagram packet. This
Example of Sending DatagramPacket by
DatagramSocket
■ //DSender.java
■ import java.net.*;
■ public class DSender{
■ public static void main(String[] args) throws Exception { ■ DatagramSocket ds = new DatagramSocket();
■ String str = "Welcome java";
■ InetAddress ip = InetAddress.getByName("127.0.0.1"); ■
■ DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
■ ds.send(dp); ■ ds.close(); ■ } ■ } 41
Example of Receiving DatagramPacket by
DatagramSocket
■ //DReceiver.java
■ import java.net.*;
■ public class DReceiver{
■ public static void main(String[] args) throws Exception { ■ DatagramSocket ds = new DatagramSocket(3000);
■ byte[] buf = new byte[1024];
■ DatagramPacket dp = new DatagramPacket(buf, 1024); ■ ds.receive(dp);
■ String str = new String(dp.getData(), 0, dp.getLength()); ■ System.out.println(str);
■ ds.close(); ■ }