Professional Documents
Culture Documents
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);}
}
}
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.
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
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.
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.
The java.net.URL class provides many methods. The important methods of URL class are given
below.
Method Description
//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
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.
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:
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
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
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 {
System.out.println("Successfully written");
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:
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...
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) IP Address
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.
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
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.
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.
Messaging Domains
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.
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.