Rahul Kumar (@rahul)
Explore Java socket programming in this blog, covering TCP connections, message exchange, and essential coding techniques for seamless client-server communication. Dive into the code now!
Socket
& ServerSocket
InputStream
and OutputStream
I am assuming that you have a basic understanding of network programming and streams in Java. This blog will not cover details about streams and network programming in Java.
We'll write two programs in Java, the Client and the Server program. Firstly server program will be started and it'll listen for connections on the specified port. Then the client program will be started and it'll send a message and the server will reply to the client.
We'll use the ServerSocket
class to create a TCP server with binding to the8080
port.
ServerSocket serverSocket = new ServerSocket(8080);
Now, a server has been created. Clients can make requests to this server on port 8080. But wait, how do we get to know that the server has received any request from the client? ServerSocket
has an accept
method that blocks the execution till any request is made. The accept method returns returns a Socket representing the connection with the client.
ServerSocket serverSocket = new ServerSocket(8080);
Socket socket = serverSocket.accept();
This serverSocket
is now ready to be connected by the clients. Let's create a client..
Client sockets are created by using the Socket
class. It accepts the host
and port
into the constructor of the server to which it needs to connect. Although it has many more methods, for which you need to consult the documentation.
Socket socket = new Socket("localhost", 8080);
Now, we know how to create a client and server. Let's write programs and execute them.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Time;
import java.time.Instant;
public class DsaByteServer {
public static void main(String[] args) throws IOException {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server Started: " + Time.from(Instant.now()));
Socket socket = serverSocket.accept();
System.out.println("Connection Received: " + Time.from(Instant.now()));
}
}
}
import java.io.IOException;
import java.net.Socket;
public class DsaByteClient {
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket("localhost", 8080)) {
// noop
}
}
}
First start DsaByteServer
using java DsaByteServer.java
and then after a few seconds start DsaByteClient
by using the java DsaByteClient.java
command.
You can see the delay between the server started and the connection received log on the terminal.
Now, we have created a simple client and server and the TCP connection is working properly. It's time to start sending messages to the server from the client. We first need to get an OutputStream
on the client socket. Then we need to write some bytes on the OutputStream
// send message to the server
OutputStream os = socket.getOutputStream();
String msg = "Rahul";
os.write(msg.getBytes());
socket.shutdownOutput();
We need to call socket.shutdownOutput()
to signal the server that there is no more input and the server can start processing.
We need to get an InputStream
on the client socket on the server side and need to read binary data from InputStream
.
InputStream is = socket.getInputStream();
int data;
StringBuilder name = new StringBuilder();
while ((data = is.read()) != -1) {
name.append((char) data);
}
System.out.println("Client Name: " + name);
InputStream.read()
reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value −1-1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
Now, let's put them together and see how it's working
DsaByteServer.java
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class DsaByteServer {
public static void main(String[] args) throws IOException {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
Socket socket = serverSocket.accept();
// reading message from socket
InputStream is = socket.getInputStream();
int data;
StringBuilder name = new StringBuilder();
while ((data = is.read()) != -1) {
name.append((char) data);
}
System.out.println("Client Name: " + name);
}
}
}
DsaByteClient.java
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class DsaByteClient {
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket("localhost", 8080)) {
// send message to the server
OutputStream os = socket.getOutputStream();
String msg = "Rahul";
os.write(msg.getBytes());
socket.shutdownOutput();
}
}
}
Output:
Upon receiving a message from the client, the server needs to respond. The server opens an OutputStream
on the client's socket, writing reply bytes to that OutputStream
. The client then consumes the reply.
package org.dsabyte.test.chat;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class DsaByteServer {
public static void main(String[] args) throws IOException {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
Socket socket = serverSocket.accept();
// reading message from socket
InputStream is = socket.getInputStream();
int data;
StringBuilder name = new StringBuilder();
while ((data = is.read()) != -1) {
name.append((char) data);
}
System.out.println("Client Name: " + name);
// send reply to the client
OutputStream os = socket.getOutputStream();
String msg = "Hello, " + name;
os.write(msg.getBytes());
socket.shutdownOutput();
}
}
}
package org.dsabyte.test.chat;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class DsaByteClient {
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket("localhost", 8080)) {
// send message to the server
OutputStream os = socket.getOutputStream();
String msg = "Rahul";
os.write(msg.getBytes());
socket.shutdownOutput();
// read reply from server
InputStream is = socket.getInputStream();
String reply = new String(is.readAllBytes());
System.out.println(reply);
}
}
}
Output
This blog guides you through the creation of a simple client-server application using Java sockets. It starts by establishing a TCP connection between the client and server. The client then sends a message to the server, signalling the end of its output using socket.shutdownOutput()
. On the server side, the message is read from the input stream using InputStream.read()
. The server replies to the client, and the client reads and prints the reply.
Add a thoughtful comment...
✨ Explore more tech insights and coding wonders with @dsabyte! Your journey in innovation has just begun. Keep learning, keep sharing, and let's continue to code a brighter future together. Happy exploring! 🚀❤️
Join the "News Later" community by entering your email. It's quick, it's easy, and it's your key to unlocking future tech revelations.
Weekly Updates
Every week, we curate and deliver a collection of articles, blogs and chapters directly to your inbox. Stay informed, stay inspired, and stay ahead in the fast-paced world of technology.
No spam
Rest assured, we won't clutter your inbox with unnecessary emails. No spam, only meaningful insights, and valuable content designed to elevate your tech experience.