Java Socket Programming


Java applications can establish network communications via TCP/IP protocols by using socket programming. The technology facilitates two-way communication between a client and a server.


notepad

Java uses java.net.Socket and java.net.ServerSocket classes to enable TCP communication.


Socket Classes in Java

Class Purpose
Socket Connects to a remote server (client side)
ServerSocket Listens for client connections (server side)
InputStream / OutputStream Used to read/write data through the socket

How TCP Socket Communication Works

  • The server establishes a ServerSocket and enters a waiting state for incoming connections.
  • The client establishes a connection to the server by creating a Socket.
  • Data transmission occurs through streams for both sending and receiving between client and server.
  • The connection between client and server remains active until one of them terminates it.

Example

Server Program

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

public class Server {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(1234);
            System.out.println("Server is waiting for client...");

            Socket socket = serverSocket.accept(); // Waits for client
            System.out.println("Client connected!");

            DataInputStream dis = new DataInputStream(socket.getInputStream());
            String clientMessage = dis.readUTF();
            System.out.println("Client says: " + clientMessage);

            dis.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
} 

Client Program

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

public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("localhost", 1234);
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

            dos.writeUTF("Hello from client!");
            dos.flush();

            dos.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output Of Server:

Server is waiting for client...
Client connected!
Client says: Hello from client!

Output Of Client

(no output; sends message silently)

Socket (Client Side)

Method Description
getInputStream() Get input stream for reading data
getOutputStream() Get output stream for writing data
close() Closes the socket

ServerSocket (Server Side)

Method Description
accept() Waits and accepts a client connection
close() Closes the server socket



Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.