Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java, socket programming is used to communicate across programs running on different JREs. It might be connection-oriented or non-connection-oriented. A socket, in general, is a method of establishing a connection between a client and a server.
Java Socket Programming
Sockets provide a means of communication between two machines using TCP. At its end of the conversation, a client application builds a socket and attempts to connect it to a server.
The server produces a socket object when the connection is established. Writing to and reading from the socket allows the client and server to interact.
When the connection is established, the server produces a socket object on its end of the conversation. The client and server can now exchange information by writing to and reading from the socket.
The java.net.Socket class represents a socket. The java.net.ServerSocket class gives the server program a way to listen to clients and connect with them.
Following are the steps to establish a TCP connection between two computers using sockets-
The server creates a ServerSocket object, which provides the port number for communication.
The server calls the accept() function of the ServerSocket class. This method waits for a client to connect to the server on the specified port before returning.
After the server has been waiting, a client creates a Socket object, providing the server name and port number to connect to.
The Socket class's constructor tries to connect the client to the provided server and port number. If communication is established, the client is now in possession of a Socket object that may communicate with the server.
The accept() method on the server-side returns a reference to a new socket on the server connected to the client's socket.
After the connections have been established, communication can occur via I/O streams. Each socket has an OutputStream as well as an InputStream. The client's OutputStream is linked to the server's InputStream, and the server's OutputStream is linked to the client's InputStream.
Because TCP is a two-way communication protocol, data may be transferred in both directions simultaneously.
Socket Class
A socket is just a communication endpoint between machines. To construct a socket, use the Socket class.
Important Methods
Method
Description
public InputStream getInputStream()
returns the InputStream attached with this socket.
public OutputStream getOutputStream()
returns the OutputStream attached with this socket.
public synchronized void close()
closes this socket
ServerSocket Class
A server socket may be created using the ServerSocket class. This object is used to communicate with the clients.
Important Methods
Method
Description
public Socket accept()
returns the socket and establishes a connection between server and client.
public synchronized void close()
closes the server socket.
Examples of Socket Programming
Creating Server:
To build the server application, we must first construct an instance of the ServerSocket class. Port number 6666 is used for communication between the client and server in this case. You can also select another port number. The accept() function sits back and waits for the client. If a client connects to the supplied port number, it returns a Socket instance.
ServerSocket newssoc=new ServerSocket(6666);
Socket soc=newssoc.accept();//establishes a connection and waits for the client
You can also try this code with Online Java Compiler
To build the client application, we must first construct an instance of the Socket class. The IP address or hostname of the server and a port number must be passed here. Because our server is operating on the same machine, we're using "localhost" here.
Socket newsoc=new Socket("localhost",6666);
You can also try this code with Online Java Compiler
Let's look at a simple Java socket programming example in which the client transmits a text and the server receives and outputs it. Also, try it on online java compiler.
Server-side:
import java.io.*;
import java.net.*;
public class server {
public static void main(String[] args) {
try {
ServerSocket ssoc = new ServerSocket(6666);
Socket soc = ssoc.accept();// establishes connection
DataInputStream dis = new DataInputStream(soc.getInputStream());
String str = (String) dis.readUTF();
System.out.println("message= " + str);
ssoc.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
You can also try this code with Online Java Compiler
To run this program, open two command prompts and run both programs simultaneously. Following the execution of the client application, a message will be shown on the server console.
Java Socket Programming Example (Read-Write both sides)
In this example, the client will first write to the server, after which the server will receive and output the text. The server will then send a message to the client, which will receive and print the text. The process continues.
Server-side:
import java.net.*;
import java.io.*;
class server {
public static void main(String args[]) throws Exception {
ServerSocket ssoc = new ServerSocket(3333);
Socket soc = ssoc.accept();
DataInputStream din = new DataInputStream(soc.getInputStream());
DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
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();
soc.close();
ssoc.close();
}
}
You can also try this code with Online Java Compiler
What is socket programming in java? In Java, socket programming is used to communicate across programs running on different JREs. It might be connected-oriented or connectionless. A socket, in general, is a method of establishing a connection between a client and a server.
Which protocol do sockets use? Transmission Control Protocol (TCP), Stream Control Transmission Protocol (SCTP), or Datagram Congestion Control Protocol (DCCP) connection-oriented sockets (DCCP).
What are the advantages of socket programming? Allows for flexible access to files and data via a network, Pooling resources, Security, Speed, Software administration is centralized, Provides protection like sending sensitive (password-protected) information and applications via a network.
Is socket A process? A socket allows two processes on the same computer or on different systems to connect with one another. A socket serves as an inter-process communicator and is regarded as the process communication's terminus. The socket communicates via a file descriptor and is commonly used in client-server applications.
What are the Disadvantages of Java sockets? Socket-based communication only allows for the transmission of raw data packets between apps. Both the client and the server must provide tools to make the data values in some way.
Key Takeaways
Cheers if you reached here! In this blog, we learned about Socket programming in Java.
We have covered the Socket and the ServerSocket classes and their uses.
We have also seen different methods inside Socket and ServerSocket classes and their uses.
Further, we saw examples of socket programming in java.
On the other hand, learning never ceases, and there is always more to learn. So, keep learning and keep growing, ninjas!
Check out the Computer Networks to know more about computer networking.