Socket Programming in java – A Complete Tutorial

0
194
socket programming in java

Socket programming in Java is a conventional way of communication between the various applications. The reliable applications are therefore running on different JRE for socket programming. Such connectivity is available in both connectionless or connection-oriented system.

JAVA Socket Programming procedure…establishing communication by two-way socket programming…TCP/IP Server Sockets…UDP Socket Programing in JAVA.

To put it simply, a Socket programming in JAVA is a robust way to secure and set up the connection between a server and a client. Therefore, without any further delay, let’s quickly plunge into the socket programming!

Image Credit: https://www.edureka.co/blog/socket-programming-in-java/

What is Socket Programming in JAVA?

It is most importantly a way of communication while connecting two nodes on a powerful network. Well, one socket hearkens to a definite port at an IP. The other socket tries to establish a connection by reaching out to the other port.

This is mainly a two-way soccer programming in JAVA, where the server creates the listener socket while the client visits the server.

If you want to know the basic criteria of socket programming then it will be better to understand the socket and server socket. Besides that, both of them are used for connection-specific socket programming.

Properly establishing the two-way communication between Client and Server in JAVA: Two-way Soccer Programming

It is easy and fast to transmit data from the server and get a quick response from the client. Moreover, the client can also transfer and receive data to-and-from.

Follow these quick and hassle-free steps to establish two-way communication:

We require extra useful streams both at the client and server. Similarly, to get data into the server, it is always an effective idea to go through a BufferedReader object. Look into the following code:

InputStream obj = s.getInputStream() ;
BufferedReader br = new BufferedReader(new InputStreamReader (obj) ;

Thereafter readLine() or read() the methodologies of BufferedReader object. It is mainly used for reading data. To transmit data from the client we may seek help of the DataOutputStream class as demonstrated in the following code:

OutputStream obj + s.getOutputStream() ;
DataOutputStream dos = new DataOutputStream(obj) ;

Now we may use the writeBytes() method of DataOutputStream. We use this to send cords in the form of bytes. If you want to do two-way soccer programming in JAVA, perform these following steps:

Creating a securing Server Program:

First, make sure to create Sever2.Java in order to get data from the client. This server2.Java class is using a BufferedReader object to send a reply by using a PrintStream object.

Server2.Java

// Server2 class that
// receives data and sends data

import java.io.*;
import java.net.*;

class Server2 {

public static void main(String args[])
throws Exception
{

// Create server Socket
ServerSocket ss = new ServerSocket(888);

// connect it to client socket
Socket s = ss.accept();
System.out.println(“Connection established”);

// to send data to the client
PrintStream ps
= new PrintStream(s.getOutputStream());

// to read data coming from the client
BufferedReader br
= new BufferedReader(
new InputStreamReader(
s.getInputStream()));

READ  Is the Redmi K20 Pro Worth Buying? K20 Pro Features, Specs & Price

// to read data from the keyboard
BufferedReader kb
= new BufferedReader(
new InputStreamReader(System.in));

// server executes continuously
while (true) {

String str, str1;

// repeat as long as the client
// does not send a null string

// read from client
while ((str = br.readLine()) != null) {
System.out.println(str);
str1 = kb.readLine();

// send to client
ps.println(str1);
}

// close connection
ps.close();
br.close();
kb.close();
ss.close();
s.close();

// terminate application
System.exit(0);

} // end of while
}
}

Image Credit: https://www.journaldev.com/741/java-socket-programming-server-client

Command to amass the Server2.Java file:

Creating the client Program:

First, you have to create Client2.Java to connect to a server. Thereafter, you can start the communication by transmitting a string to the server. Now the server will send you a quick response to the client. The program is gradually going to terminate when the client types the ‘exit’.

Client2.Java

// Client2 class that
// sends data and receives also

import java.io.*;
import java.net.*;

class Client2 {

public static void main(String args[])
throws Exception
{

// Create client socket
Socket s = new Socket(“localhost”, 888);

// to send data to the server
DataOutputStream dos
= new DataOutputStream(
s.getOutputStream());

// to read data coming from the server
BufferedReader br
= new BufferedReader(
new InputStreamReader(
s.getInputStream()));

// to read data from the keyboard
BufferedReader kb
= new BufferedReader(
new InputStreamReader(System.in));
String str, str1;

// repeat as long as exit
// is not typed at client
while (!(str = kb.readLine()).equals(“exit”)) {

// send to the server
dos.writeBytes(str + “\n”);

// receive from the server
str1 = br.readLine();

System.out.println(str1);
}

// close connection.
dos.close();
br.close();
kb.close();
s.close();
}
}

Command to amass the Client2.Java file:

Output:

Make sure to run both System2.Java and Client2.Java in two isolated command prompt windows. This has to be done to execute Server2 and Client2 classes.

 

Some important fundamentals of UDP Socket Programing in JAVA:

UDP socket programming in JAVA is performed for creating communication between a server and client. UDP is a User Datagram Protocol that allows data transmission. Moreover, it is a connectionless protocol. Just go through the several phases to understand its function:

How does UDP socket communication happen(socket programming in java)?

The DatagramSocket and DatagramPacket in Java support prefer to take advantage of UDP socket communication. Most importantly, there is a server and client that communicates with each other with the help of a UDP socket.

Therefore, the socket programming in JAVA server accepts String type data from the client. It again transmits the capitalized string back to the client quickly.

The leading steps of creating a UDP socket server in Java

How to run these programs?

Once the server and client both have created, it’s time to run the program. At first, run the UDPServer.Java program and thereafter run UDPClient.Java.

After you run these programs, you will see the subsequent outputs. These outputs ensure effective socket programming in JAVA communication. This has been established between the UDPServer and UDPClient.

UDPServer.Java:
UDPClient.Java:

TCP/IP Server Sockets – Java Networking(socket programming in java):

The java.net package possesses innumerable interfaces and a collection of classes that offer us to write programs. Besides that, it provides the details of low-level communication and concentrates on solving the problem.

Similarly, java.net provides various facilitations for the most common network protocol:

TCP: It stands for Transmission Control Protocol. TCP helps to maintain dependable communication between two applications. Despite that, it is also used as an Internet protocol, which is often denoted as TCP/IP.

READ  Tips to fix err_connection_timed_out error

TCP/IP Server Socket Fundamentals(socket programming in java):

This Serversocket provides the appropriate niche to jot down everything about socket programming in JAVA. The leading job of a server socket lies in waiting for incoming calls and reply accordingly. TCP/IP server socket in Java mainly runs on the quick server and listens to the incoming TCP connections.

Whenever a ClientSocket tries to get connected to that port, the server wakes up quickly. It helps to negotiate the powerful connection by inaugurating a socket between two hosts.

Image Credit: https://www.geeksforgeeks.org/introducing-threads-socket-programming-java/

This powerful socket programming in JAVA helps to transmit data to the clients. Quickly take a glance at the workflow of the server program which is shown below:

Create a robust server socket on a specific port.
Consider any of the connections provided to that port.
If a connection becomes successful, make sure to get the host of stream objects from the socket. Thereafter, communicate with the client.

Please ensure to establish those connections according to the agreed protocol.
After that, shut down the connection.
Wait (if necessary) for more communication attempts.

An example of a TCP/IP ServerSocket object(socket programming in java):

Now quickly look into the following code showing how a ServerSocket can be created. Make sure to go through the most of the functionality and it is very identical to the client program. That particular element that denotes this class as the server is known as the ServerSocket object.

 

package tcpsocketdemo;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Server extends JFrame {
private static final int PORT = 12345;
private static final int BACKLOG = 100;

private final JTextField msgField =
new JTextField();
private final JTextArea msgDisplayArea =
new JTextArea();
private ObjectOutputStream out;
private ObjectInputStream in;
private ServerSocket server;
private Socket socket;

public Server() {
super(“Server”);
msgField.setEditable(false);
msgField.addActionListener((ActionEvent e) -> {
send(e.getActionCommand());
msgField.setText(“”);
throw new UnsupportedOperationException
(“Not supported yet.”);
});
super.add(msgField, BorderLayout.NORTH);
super.add(new JScrollPane(msgDisplayArea));
super.setSize(400, 250);
super.setVisible(true);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void startServer() {
try {
server = new ServerSocket(PORT, BACKLOG);
while (true) {
try {
waitForCall();
setIOStreams();
processCall();
} catch (EOFException ex) {
showMsg(“\nServer connection closed”);
} finally {
endCall();
}
}
} catch (IOException e) {
}
}

private void setIOStreams() throws IOException {
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
in = new ObjectInputStream(socket.getInputStream());
showMsg(“\nI/O Stream is ready.”);
}

private void waitForCall() throws IOException {
showMsg(“\nWaiting for call…”);
socket = server.accept();
showMsg(“Connection accepted from ” +
socket.getInetAddress().getHostName());
}

private void processCall() {
String msg = “Connection established successfully.”;
send(msg);
setMsgFieldEditable(true);
do {
try {
msg = (String) in.readObject();
showMsg(“\n” + msg);
} catch (ClassNotFoundException | IOException ex) {
showMsg(“\nInvalid object received”);
}
} while (!msg.equals(“Client# bye”));
}

private void showMsg(final String msg) {
SwingUtilities.invokeLater(() -> {
msgDisplayArea.append(msg);
});
}

private void setMsgFieldEditable(final boolean flag) {
SwingUtilities.invokeLater(() -> {
msgField.setEditable(flag);
});
}

private void send(String msg) {
try {
out.writeObject(“\nServer# ” + msg);
out.flush();
showMsg(“\nServer# ” + msg);
} catch (IOException ex) {
msgDisplayArea.append(“Error: ” + ex);
}
}

private void endCall() {
showMsg(“\nConnection closed”);
setMsgFieldEditable(false);
try {
out.close();
in.close();
socket.close();
} catch (IOException ex) {
}
}
}

packagetcpsocketdemo;
public class TCPSocketServer{

public static void main(String[] args) {
Server app=new Server();
app.startServer();
}
}

Conclusion:

Well, this article upon socket programming in Java demonstrates two-way socket programming, UDP programming, and TCP/IP ServerSocket programming in Java. We positively hope this article is useful and as well as informative. Just go through the aforementioned points and you will get efficient information regarding these topics.

Leave a reply