Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Socket Programming in Java

1. Introduction

Socket programming in Java allows communication between devices over a network. It uses the TCP/IP protocol suite, enabling reliable, ordered, and error-checked delivery of a stream of bytes.

2. Key Concepts

  • Socket: An endpoint for sending or receiving data.
  • Server Socket: Listens for incoming connections.
  • Client Socket: Connects to a server socket.
  • Port: A communication endpoint for applications.
  • IP Address: Identifies a device on the network.

3. Client-Server Model

The client-server model is a distributed application structure that partitions tasks between service providers (servers) and service requesters (clients).


                graph TD;
                    A[Client] -->|Connects| B[Server];
                    B -->|Sends Data| A;
            

4. Socket Creation

To create a socket in Java, follow these steps:

  1. Import the required packages:
  2. Create a socket using new Socket(host, port).
  3. Use input/output streams to read/write data.
  4. Close the socket after communication is finished.

5. Code Example

Server Code


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

public class Server {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(12345)) {
            System.out.println("Server listening on port 12345");
            Socket socket = serverSocket.accept();
            System.out.println("Client connected");

            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            String message = in.readLine();
            System.out.println("Received: " + message);
            out.println("Hello Client!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
                

Client Code


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

public class Client {
    public static void main(String[] args) {
        try (Socket socket = new Socket("localhost", 12345)) {
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out.println("Hello Server!");
            String response = in.readLine();
            System.out.println("Server replied: " + response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
                

6. Best Practices

  • Always close sockets in a finally block or use try-with-resources.
  • Handle exceptions properly to avoid unexpected crashes.
  • Use a separate thread for each client to handle multiple clients simultaneously.
  • Implement timeouts to enhance the robustness of your application.

7. FAQ

What is a socket?

A socket is a software structure that allows communication between two machines over a network.

What is a ServerSocket?

A ServerSocket listens for incoming connections from clients and establishes a communication channel.

Can a server handle multiple clients?

Yes, by using threads or asynchronous programming, a single server can manage multiple client connections.