In Java, a socket is one end of a two-way communication channel between two network-connected applications. It is used to communicate across programs running on different JREs (Java Runtime Environments).
Table of Contents
A socket, in general, is a method of establishing a connection between a client and a server. It might be connection-oriented or non-connection-oriented.
Computers must establish a connection for connection-oriented protocols before transferring data. The only connectionless protocol choice is UDP (User Datagram Protocol).
To further demonstrate sockets, we will use the client/server architecture. The client and server correspond by writing to and reading from the socket interrelation.
A socket is a communication endpoint that connects two devices on a network. It has a port number that the TCP/IP layer can use to identify the receiving application.
A port number and an IP address are frequently included in an endpoint.
Two communication protocols that can be used for socket programming are User Datagram Protocol (UDP) and Transfer Control Protocol (TCP).
The primary distinction is that UDP is connectionless, so there is no session between the client and the server.
Also Read: Guide to hashCode() in Java
Still, TCP is connection-oriented, which means communication must first be established between the client and the server.
This article provides an overview of Java socket programming over TCP/IP networks and examples of client/server Java systems. Let’s get into it.
The following steps are used to build a socket connection in Java:
The OutputStream of the client connects with the InputStream of the server. While the server’s OutputStream communicates with the InputStream of the client.
A stream is essentially a collection of data that has been ordered. There are two primary sorts of streams:
A character stream is written in human-readable characters, whereas a byte stream is written in machine-readable symbols.
A server usually operates on a networked computer and has a socket that is tied to a specific port number. In Java, the package java.net is used for socket programming.
This package contains two classes: The Socket class and the ServerSocket class.
In our scenario, we’ll run the server on the same machine as the client and connect to port 6666:
ServerSocket sSocket = new ServerSocket(int portno); ServerSocket sSocket = new ServerSocket(6666);
The server waits for a client to request a connection by listening to the socket.
This occurs in the next step:
Socket cSocket = sSocket.accept();
The client must know the hostname or IP address of the computer on which the server is executing, as well as the server’s listening port number.
The client tries to connect with the server on the server’s machine and port to issue a connection request:
Socket cSocket = new Socket("localhost",6666);
To construct a socket, utilize the Socket class.
Let’s start with the most fundamental scenarios involving a client and a server. It will be a two-way communication application in which the client will greet the server, and the server will answer.
With the following code, we’ll develop the server program in a class called WelcomeServer.java.
import java.io.*; import java.net.*; public class WelcomeServer { private ServerSocket sSocket; private Socket cSocket; private PrintWriter out; private BufferedReader in; public void start(int portno) { sSocket = new ServerSocket(portno); cSocket = sSocket.accept(); out = new PrintWriter(cSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader (cSocket.getInputStream())); String welcoming = in.readLine(); if ("hello server".equals(welcoming)) { out.println("hey client"); } else { out.println("unrecognised welcoming"); } } public void close() { in.close(); out.close(); cSocket.close(); sSocket.close(); } public static void main(String[] args) { WelcomeServer server=new WelcomeServer(); server.establish(6666); } }
Now we will create a client called WelcomeClient.java with this code:
public class WelcomeClient { private Socket cSocket; private PrintWriter out; private BufferedReader in; public void startConnection(String ip, int port) { cSocket = new Socket(ip, port); out = new PrintWriter(cSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader (cSocket.getInputStream())); } public String transmitMessage(String msg) { out.println(msg); String response = in.readLine(); return response; } public void stopConnection() { in.close(); out.close(); cSocket.close(); } }
Next, using a unit test, we’ll send a welcome to the server, confirming that the server responds with a greeting:
@Test public void givenGreetingClient_whenServerRespondsWhenStarted_thenCorrect() { WelcomeClient client = new WelcomeClient(); client.startConnection("127.0.0.1", 6666); String resp = client.sendMessage("hey server"); assertEquals("hey client", resp); }
Socket programming is only the beginning! Sockets are the essential “things” that enable your computer to communicate over a network.
See Also: Introduction to Java Primitives
Sockets and Java allow us to accomplish a variety of things. It would be best if you had mastered the fundamentals of socket programming in Java by now.
You may experiment with things like developing a chat client or anything similar. You may create additional highly productive apps using sockets and the TCP/IP protocol.
I am a senior technical project manager in a reputable US based software development company. I have been developing and managing innovative solutions for multinational companies, deployed software and systems. I am responsible for full life cycle development of next-generation software, from initial requirement gathering to design, coding, testing, documentation and implementation. Being in technology I love to write about it.
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use