- Networking in Java
- Networking Terminology
- Java Socket Programming
- Socket Class
- Socket Class Constructors
- ServerSocket Class
- ServerSocket Class Constructors
- Example: Implementing the ServerSocket class & its methods
- Example: Generating Request and Response in Client and server Application
- Networking Basics
- TCP
- UDP
- Understanding Ports
- Networking Classes in the JDK
Networking in Java
Networking is the concept of connecting multiple remote or local devices together. Java program communicates over the network at application layer.
All the Java networking classes and interfaces use java.net package. These classes and interfaces provide the functionality to develop system-independent network communication.
The java.net package provides the functionality for two common protocols:
TCP (Transmission Control Protocol)
TCP is a connection based protocol that provides a reliable flow of data between two devices. This protocol provides the reliable connections between two applications so that they can communicate easily. It is a connection based protocol.
UDP (User Datagram Protocol)
UDP protocol sends independent packets of data, called datagram from one computer to another with no guarantee of arrival. It is not connection based protocol.
Networking Terminology
i) Request and Response
When an input data is sent to an application via network, it is called request.
The output data coming out from the application back to the client program is called response.
ii) Protocol
A protocol is basically a set of rules and guidelines which provides the instructions to send request and receive response over the network.
For example: TCP, UDP, SMTP, FTP etc.
iii) IP Address
IP Address stands for Internet protocol address. It is an identification number that is assigned to a node of a computer in the network.
For example: 192.168.2.01
Range of the IP Address
0.0.0.0 to 255.255.255.255
iv) Port Number
The port number is an identification number of server software. The port number is unique for different applications. It is a 32-bit positive integer number having between ranges 0 to 65535.
v) Socket
Socket is a listener through which computer can receive requests and responses. It is an endpoint of two way communication link. Every server or programs runs on the different computers that has a socket and is bound to the specific port number.
Java Socket Programming
Socket provides an endpoint of two way communication link using TCP protocol. Java socket can be connection oriented or connection less. TCP provides two way communication, it means data can be sent across both the sides at same time.
Socket Class
The java.net.Socket class is used to create a socket so that both the client and the server can communicate with each other easily. A socket is an endpoint for communication between two computers. The Socket class inherits the Object class and implements the Closeable interface.
Socket Class Constructors
Constructor | Description |
---|---|
Socket() | Creates an unconnected socket, with the system-default type of SocketImpl. |
public Socket(InetAddress address, int port) | Creates a stream socket with specified IP address to the specified port number. |
public Socket(InetAddress host, int port, boolean stream) | Uses the DatagramSocket. |
public Socket(InetAddress address, int port, InetAddress localAddr, int local port) | Creates a connection with specified remote address and remote port. |
public Socket(Proxy, proxy) | Creates a connectionless socket specifying the type of proxy. |
protected Socket(SocketImpl impl) | Creates a connectionless Socket with a user-specified SocketImpl. |
ServerSocket Class
Socket class is used to create socket and send the request to the server. Java ServerSocket class waits for request to come over the network. It works on the basis of request and then returns a result to the request. It implements the Closeable interface.
ServerSocket Class Constructors
Constructor | Description |
---|---|
ServerSocket() | Creates an unbound server socket. |
ServerSocket(int port) | Creates a server socket, bound to the specified port. |
ServerSocket(int port, int backlog) | Creates a server socket, bound to the specified port, with specified local port. |
ServerSocket(int port, int backlog, inetAddress bindAddrs) | Creates a server socket, bound to specified port, listen backlog, and IP address. |
Example: Implementing the ServerSocket class & its methods
import java.io.*;
import java.net.*;
public class SerSocket
public static void main(String args[])
int port=8080;
try
ServerSocket ss = new ServerSocket(port);
System.out.println(«Server initialized on port: » + port);
ss.getLocalPort();
ss.getInetAddress();
while(true)
ss.accept();
>
>
catch (SocketException e)
System.out.println(«Socket error»);
>
catch ( IOException e)
System.out.println(«An I/O Exception Occurred!»);
>
>
>
Output:
Server initialized on port: 8080
Example: Generating Request and Response in Client and server Application
import java.io.InputStream;
import java.io.DataInputStream;
import java.net.Socket;
public class ClientDemo
public static void main(String args[])
try
Socket s = new Socket(«localhost», 7777);
InputStream in = s.getInputStream();
DataInputStream dis = new DataInputStream(in);
String msg = dis.readLine();
System.out.println(«Server message is: «+ msg);
dis.close();
s.close();
>
catch(Exception e)
e.printStackTrace();
>
>
>
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.net.ServerSocket;
public class ServerDemo
public static void main(String args[])
try
ServerSocket ss = new ServerSocket(7777);
System.out.println(«Server is ready.»);
Socket s = ss.accept();
System.out.println(«COnnection created.»);
System.out.println(«Sent message to client.»);
OutputStream out = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeBytes(«Welcome»);
dos.close();
s.close();
ss.close();
>
catch(Exception e)
e.printStackTrace();
>
>
>
Networking Basics
Computers running on the Internet communicate to each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:
When you write Java programs that communicate over the network, you are programming at the application layer. Typically, you don’t need to concern yourself with the TCP and UDP layers. Instead, you can use the classes in the java.net package. These classes provide system-independent network communication. However, to decide which Java classes your programs should use, you do need to understand how TCP and UDP differ.
TCP
When two applications want to communicate to each other reliably, they establish a connection and send data back and forth over that connection. This is analogous to making a telephone call. If you want to speak to Aunt Beatrice in Kentucky, a connection is established when you dial her phone number and she answers. You send data back and forth over the connection by speaking to one another over the phone lines. Like the phone company, TCP guarantees that data sent from one end of the connection actually gets to the other end and in the same order it was sent. Otherwise, an error is reported.
TCP provides a point-to-point channel for applications that require reliable communications. The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that require a reliable communication channel. The order in which the data is sent and received over the network is critical to the success of these applications. When HTTP is used to read from a URL, the data must be received in the order in which it was sent. Otherwise, you end up with a jumbled HTML file, a corrupt zip file, or some other invalid information.
TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data between two computers.
UDP
The UDP protocol provides for communication that is not guaranteed between two applications on the network. UDP is not connection-based like TCP. Rather, it sends independent packets of data, called datagrams, from one application to another. Sending datagrams is much like sending a letter through the postal service: The order of delivery is not important and is not guaranteed, and each message is independent of any other.
UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.
For many applications, the guarantee of reliability is critical to the success of the transfer of information from one end of the connection to the other. However, other forms of communication don’t require such strict standards. In fact, they may be slowed down by the extra overhead or the reliable connection may invalidate the service altogether.
Consider, for example, a clock server that sends the current time to its client when requested to do so. If the client misses a packet, it doesn’t really make sense to resend it because the time will be incorrect when the client receives it on the second try. If the client makes two requests and receives packets from the server out of order, it doesn’t really matter because the client can figure out that the packets are out of order and make another request. The reliability of TCP is unnecessary in this instance because it causes performance degradation and may hinder the usefulness of the service.
Another example of a service that doesn’t need the guarantee of a reliable channel is the ping command. The purpose of the ping command is to test the communication between two programs over the network. In fact, ping needs to know about dropped or out-of-order packets to determine how good or bad the connection is. A reliable channel would invalidate this service altogether.
The UDP protocol provides for communication that is not guaranteed between two applications on the network. UDP is not connection-based like TCP. Rather, it sends independent packets of data from one application to another. Sending datagrams is much like sending a letter through the mail service: The order of delivery is not important and is not guaranteed, and each message is independent of any others.
Many firewalls and routers have been configured not to allow UDP packets. If you’re having trouble connecting to a service outside your firewall, or if clients are having trouble connecting to your service, ask your system administrator if UDP is permitted.
Understanding Ports
Generally speaking, a computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection. However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data? Through the use of ports.
Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application.
In connection-based communication such as TCP, a server application binds a socket to a specific port number. This has the effect of registering the server with the system to receive all data destined for that port. A client can then rendezvous with the server at the server’s port, as illustrated here:
The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.
In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure:
Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 — 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services. These ports are called well-known ports. Your applications should not attempt to bind to them.
Networking Classes in the JDK
Through the classes in java.net , Java programs can use TCP or UDP to communicate over the Internet. The URL , URLConnection , Socket , and ServerSocket classes all use TCP to communicate over the network. The DatagramPacket , DatagramSocket , and MulticastSocket classes are for use with UDP.