You are on page 1of 15

Unit II

NETWORK PROGRAMMING IN JAVA

2.1 Introduction to Sockets


A socket is one endpoint of a two-way communication link between two programs
running on the network. A socket is bound to a port number so that the TCP layer can identify
the application that data is destined to be sent to. A socket connection means the two
machines have information about each other’s network location (IP Address) and TCP port.
The java.net.Socket class represents a Socket. To open a socket

Socket socket = new Socket(“127.0.0.1”, 5000)


 The first argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where
code will run on the single stand-alone machine).
 The second argument – TCP Port. (Just a number representing which application to run on
a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

Communication - To communicate over a socket connection, streams are used to both input
and output the data.
Closing the connection - The socket connection is closed explicitly once the message to the
server is sent.

Server Program
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);}
}
}
Client Program

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 DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

2.2 Types of Socket:

1. Datagram Sockets: Datagram sockets allow processes to use the User Datagram Protocol
(UDP). It is a two-way flow of communication or messages. It can receive messages in a
different order from the sending way and also can receive duplicate messages. These sockets
are preserved with their boundaries. The socket type of datagram socket is SOCK_DGRAM.

2. Stream Sockets: Stream socket allows processes to use the Transfer Control Protocol
(TCP) for communication. A stream socket provides a sequenced, constant or reliable, and
two-way (bidirectional) flow of data. After the establishment of connection, data can be read
and written to these sockets in a byte stream. The socket type of stream socket is
SOCK_STREAM.

3. Raw Sockets: Raw Socket provide user access to the Internet Control Message Protocol
(ICMP). Raw sockets are not used for most applications. These sockets are the same as the
datagram oriented, their characteristics are dependent on the interfaces. They provided
support in developing new communication protocols or for access to more facilities of an
existing protocol. Only the superusers can access the Raw Sockets. The socket type of Raw
Socket is SOCK_RAW.

4. Multicast Socket : A MulticastSocket is a (UDP) DatagramSocket, with additional


capabilities for joining "groups" of other multicast hosts on the internet. A multicast group is
specified by a class D IP address and by a standard UDP port number. Class D IP addresses are
in the range 224.0. 0.0 to 239.255.
5. Secured Socket : The Java Secure Socket Extension (JSSE) enables secure Internet
communications. It provides a framework and an implementation for a Java version of the TLS
and DTLS protocols and includes functionality for data encryption, server authentication,
message integrity, and optional client authentication.

6. Custom Socket : Socket classes are used to represent the connection between a client
program and a server program. The java.net package provides two classes--Socket and
ServerSocket

Advantages of Java Sockets

 Platform Independence − One of the biggest advantages of Java Sockets is that they are
platform-independent. This means that the same Java code can be run on multiple
operating systems and devices without the need for modification. This allows for easy
deployment of network-based applications across different systems and ensures that
the application can be run on different devices without the need for platform-specific
code.
 Easy to Use − Java Sockets are also relatively easy to use, even for developers who are
new to network programming. The Java API provides a simple, consistent interface for
creating and managing sockets, which makes it easy to implement network-based
applications without needing to understand the underlying network protocols.
 Scalability − Java Sockets are highly scalable, making them suitable for large-scale
network-based applications. They can easily handle thousands of simultaneous
connections and can be used to create distributed systems that can handle high levels of
traffic.
 Security − Java Sockets provide built-in support for secure communication, including SSL
and TLS encryption. This makes it easy to create secure network-based applications and
ensures that sensitive data is protected while in transit.
 Multithreading − Java Sockets support multithreading, which means that multiple
threads can be used to handle multiple connections simultaneously. This improves the
performance of network-based applications and allows them to handle a large number
of requests without becoming overloaded.

Examples of Java Socket Applications

 Chat Applications − Java Sockets are often used to create chat applications, such as
instant messaging programs and online chat rooms. These types of applications typically
use a client-server architecture, where clients connect to a central server to send and
receive messages.
 File Transfer Applications − Java Sockets can also be used to create file transfer
applications, such as peer-to-peer file sharing programs. These types of applications use
a peer-to-peer architecture, where each device acts as both a client and a server. This
allows for direct communication between devices, which can improve the speed and
reliability of file transfers.
 Remote Control Applications − Java Sockets can also be used to create remote control
applications, such as remote desktop software. These types of applications use a client-
server architecture, where a client connects to a remote server to control the desktop of
the server. This allows users to access and control their desktop from any device with an
internet connection.
 Multiplayer Games − Java Sockets are also commonly used to create multiplayer games,
such as online role-playing games and first-person shooters. These types of applications
typically use a client-server architecture, where clients connect to a central server to
play the game. The server acts as the intermediary between clients, handling
communication and game logic.
 IoT Applications − Java Sockets can also be used in IoT (Internet of Things) applications,
such as smart home systems. These types of applications use a client-server
architecture, where IoT devices connect to a central server to send and receive data.
This allows for remote monitoring and control of the devices, as well as data collection
and analysis.

2.3 Java URL


1. The URL class in java is a getaway to access any resource available on the web or
internet. URL is a Uniform Resource Locator that points to the resource like file,
directory, or image on the World Wide Web(www).

A URL contains many information:

2. Protocol: In this case, http is the protocol.


3. Server name or IP Address: In this case, www.javatpoint.com is the server name.
4. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is
not mentioned in the URL, it returns -1.
5. File Name or directory name: In this case, index.jsp is the file name.
2.4 Commonly used methods of Java URL class

The java.net.URL class provides many methods. The important methods of URL class are given
below.

Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.

Example of Java URL class

//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());

}catch(Exception e){System.out.println(e);}
}
}

Output:

Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

2.5 Reading and Writing Data between server and Client

This client program is straightforward and simple because the echo server implements a simple
protocol. The client sends text to the server, and the server echoes it back. When your client
programs are talking to a more complicated server such as an HTTP server, your client program
will also be more complicated. However, the basics are much the same as they are in this
program:

1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol.
4. Close the streams.
5. Close the socket.

Java API that can be used to read and write files in Java:
FileReader, FileInputStream, Scanner, FileWriter, FileOutputStream, etc.

FileReader - Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class. It is character-oriented class which is used for file handling
in java.

Constructors of FileReader class

Constructor Description

FileReader(String It gets filename in string. It opens the given file in read mode. If file
file) doesn't exist, it throws FileNotFoundException.

FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file
doesn't exist, it throws FileNotFoundException.

import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}

FileInputStream - Java FileInputStream class obtains input bytes from a file. It is used for
reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can
also read character-stream data. But, for reading streams of characters, it is recommended to
use FileReader class.

Scanner : The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read Strings:

import java.util.Scanner; // Import the Scanner class

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output user input
}
}

Java FileWriter class of java.io package is used to write data in character form to file. Java
FileWriter class is used to write character-oriented data to a file. It is a character-oriented
class that is used for file handling in java.
 This class inherits from OutputStreamWriter class which in turn inherits from the Writer
class.
Java FileWriter Class Declaration

public class FileWriter extends OutputStreamWriter

// Java program to create a text File using FileWriter

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
class GFG {
public static void main(String[] args)
throws IOException
{
// initialize a string
String str = "ABC";
try {

// attach a file to FileWriter


FileWriter fw
= new FileWriter("D:/data/file.txt");

// read each character from string and write


// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));

System.out.println("Successfully written");

// close the file


fw.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}

Basic Methods of FileWriter Class

1. Write()
 write(int a): This method writes a single character specified by int a.
 write(String str, int pos, int length): This method writes a portion of the string from
position
 write(char ch[]): This method writes an array of characters specified by ch[].
 write(String st): This method writes a string value specified by ‘st’ into the file.

FileOutputStream:

FileOutputStream is an outputstream for writing data/streams of raw bytes to file or storing


data to file. FileOutputStream is a subclass of OutputStream. To write primitive values into a
file, we use FileOutputStream class.

Through the above image, we can understand that when we run the java program, the data is
stored in the RAM. Now, suppose the variable data stored in RAM, we want to access that
data and bring it to a file in our hard disk. So, we will create an object of OutputStream in the
RAM and that will point to a file referencing to hard disk.

Declaration:
public class FileOutputStream extends OutputStream

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

OUTPUT
Success...

2.6 Configuring the Network Connection

When computing devices such as laptops, desktops, servers, smartphones, and tablets and an
eternally-expanding arrangement of IoT gadgets such as cameras, door locks, doorbells,
refrigerators, audio/visual systems, thermostats, and various sensors are sharing information
and data with each other is known as networking.

Socket Programming

Java Socket programming is practiced for communication between the applications working
on different JRE. Sockets implement the communication tool between two computers using
TCP. Java Socket programming can either be connection-oriented or connection-less. In
Socket Programming, Socket and ServerSocket classes are managed for connection-oriented
socket programming. However, DatagramSocket and DatagramPacket classes are utilized for
connection-less socket programming.
A client application generates a socket on its end of the communication and strives to
combine that socket with a server. When the connection is established, the server generates
an object of socket class on its communication end. The client and the server can now
communicate by writing to and reading from the socket.
The java.net.Socket class describes a socket, and the java.net.ServerSocket class implements
a tool for the server program to host clients and build connections with them.

Java Networking

Networking supplements a lot of power to simple programs. With networks, a single program
can regain information stored in millions of computers positioned anywhere in the world.
Java is the leading programming language composed from scratch with networking in mind.
Java Networking is a notion of combining two or more computing devices together to share
resources.
The java.net package of the J2SE APIs comprises various classes and interfaces that execute
the low-level communication features, enabling the user to formulate programs that focus on
resolving the problem.
Common Network Protocols

1. Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol allows


secure communication between different applications. TCP is a connection-oriented
protocol which means that once a connection is established, data can be transmitted
in two directions.

2. User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a connection-less


protocol that allows data packets to be transmitted between different applications.
UDP is a simpler Internet protocol in which error-checking and recovery services are
not required.

Java Networking Terminology

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:

o TCP
o FTP
o Telnet
o SMTP
o POP etc.

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 address.

For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.

5) Socket - A socket is an endpoint between two way communications.

Java Networking classes

The classes covered in the java.net package are given as follows –

CacheRequest – The CacheRequest class is used in java whenever there is a need to


store resources in ResponseCache.
CookieHandler – The CookieHandler class is used in Java to implement a callback
mechanism for securing up an HTTP state management policy implementation inside
the HTTP protocol handler.
DatagramPacket – The DatagramPacket class is used to provide a facility for the
connectionless transfer of messages from one system to another.
InetAddress – The InetAddress class is used to provide methods to get the IP address
of any hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number.
InetAddress can handle both IPv4 and IPv6 addresses.
Socket – The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations.
Proxy – A proxy is a changeless object and a kind of tool or method or program or
system, which serves to preserve the data of its users and computers.
URL – The URL class in Java is the entry point to any available sources on the internet.
A Class URL describes a Uniform Resource Locator, which is a signal to a “resource” on
the World Wide Web.

2.7 Telnet Application


o The main task of the internet is to provide services to users. For example, users want to
run different application programs at the remote site and transfers a result to the local
site. This requires a client-server program such as FTP, SMTP. But this would not allow
us to create a specific program for each demand.
o The better solution is to provide a general client-server program that lets the user
access any application program on a remote computer. Therefore, a program that
allows a user to log on to a remote computer. A popular client-server program Telnet is
used to meet such demands. Telnet is an abbreviation for Terminal Network.
o Telnet provides a connection to the remote computer in such a way that a local terminal
appears to be at the remote side.

At the local site

The user sends the keystrokes to the terminal driver, the characters are then sent to the
TELNET client. The TELNET client which in turn, transforms the characters to a universal
character set known as network virtual terminal characters and delivers them to the
local TCP/IP stack

At the remote site

The commands in NVT forms are transmitted to the TCP/IP at the remote machine.
Here, the characters are delivered to the operating system and then pass to the TELNET
server. The TELNET server transforms the characters which can be understandable by a
remote computer.

o The network virtual terminal is an interface that defines how data and commands are
sent across the network.
o In today's world, systems are heterogeneous. For example, the operating system
accepts a special combination of characters such as end-of-file token running a DOS
operating system ctrl+z while the token running a UNIX operating system is ctrl+d.
o TELNET solves this issue by defining a universal interface known as network virtual
interface.
o The TELNET client translates the characters that come from the local terminal into NVT
form and then delivers them to the network. The Telnet server then translates the data
from NVT form into a form which can be understandable by a remote computer.

2.8 Java Message Service


The Java Message Service (JMS) makes it easy to develop enterprise applications that
asynchronously send and receive business data and events. It defines a common enterprise
messaging API that is designed to be easily and efficiently supported by a wide range of
enterprise messaging products.

Requirement of JMS

Generally, user sends message to application. But, if we want to send message from one
application to another, we need to use JMS API.

Consider a scenario, one application A is running in INDIA and another application B is running
in USA. To send message from A application to B, we need to use JMS.

Advantage of JMS

1) Asynchronous: To receive the message, client is not required to send request. Message will
arrive automatically to the client.

2) Reliable: It provides assurance that message is delivered.

Messaging Domains

There are two types of messaging domains in JMS.


1. Point-to-Point Messaging Domain
2. Publisher/Subscriber Messaging Domain

1) Point-to-Point (PTP) Messaging Domain

In PTP model, one message is delivered to one receiver only. Here, Queue is used as a message
oriented middleware (MOM). The Queue is responsible to hold the message until receiver is
ready. In PTP model, there is no timing dependency between sender and receiver.

2) Publisher/Subscriber (Pub/Sub) Messaging Domain

In Pub/Sub model, one message is delivered to all the subscribers. It is like broadcasting.
Here, Topic is used as a message oriented middleware that is responsible to hold and deliver
messages.

In PTP model, there is timing dependency between publisher and subscriber.

You might also like