Java Socket Class

Socket is a fundamental building block of network communication, allowing different computers to exchange data over a network.

In Java,java.net.SocketThe Socket class provides client-side functionality for implementing network communication.

You can think of a Socket as a connection between two phones:

  • One end is the client (the caller)
  • The other end is the server (the person answering the call)
  • Once the connection is established, both parties can send and receive information to and from each other

Basic Usage of the Socket Class

Creating a Socket Connection

To create a Socket connection, you need to specify the server's address and port:

Example

try {
    // Connect to port 8080 on localhost
    Socket socket = new Socket("localhost", 8080);
   
    // Use the socket for communication...
   
    // Close the connection
    socket.close();
} catch (IOException e) {
    e.printStackTrace();
}

Main Methods

The Socket class provides several important methods:

Method Description
getInputStream() Get the input stream for receiving data
getOutputStream() Get the output stream for sending data
close() Close the Socket connection
isConnected() Check whether the connection is established
setSoTimeout(int timeout) Set the timeout (milliseconds)

Implementing Client-Server Communication

Client Example

Example

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

public class Client {
    public static void main(String[] args) {
        try {
            // 1. Create a Socket connection
            Socket socket = new Socket("localhost", 12345);
           
            // 2. Get the output stream and send data to the server
            PrintWriter out = new PrintWriter(
                socket.getOutputStream(), true);
            out.println("Hello Server!");
           
            // 3. Get the input stream and receive the server's response
            BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
            String response = in.readLine();
            System.out.println("Server response: " + response);
           
            // 4. Close the connection
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Server-side Example

On the server side, you need to use theServerSocketServerSocket class:

Example

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

public class Server {
    public static void main(String[] args) {
        try {
            // 1. Create a ServerSocket and listen on the specified port
            ServerSocket serverSocket = new ServerSocket(12345);
            System.out.println("Server started. Waiting for client...");
           
            // 2. Wait for a client connection
            Socket clientSocket = serverSocket.accept();
            System.out.println("Client connected.");
           
            // 3. Get the input stream and read the client's message
            BufferedReader in = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));
            String message = in.readLine();
            System.out.println("Client says: " + message);
           
            // 4. Get the output stream and send a response to the client
            PrintWriter out = new PrintWriter(
                clientSocket.getOutputStream(), true);
            out.println("Hello Client!");
           
            // 5. Close the connection
            clientSocket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Advanced Features of Socket

Setting Timeouts

Example

Socket socket = new Socket();
// Set the connection timeout to 5 seconds
socket.connect(new InetSocketAddress("example.com", 80), 5000);
// Set the read timeout to 3 seconds
socket.setSoTimeout(3000);

Keeping the Connection Alive

Example

// Enable the TCP keep-alive mechanism
socket.setKeepAlive(true);

Buffer Size

Example

// Set the receive buffer size (bytes)
socket.setReceiveBufferSize(8192);
// Set the send buffer size (bytes)
socket.setSendBufferSize(8192);

Common Problems and Solutions

Connection Refused

  • Check whether the server is running
  • Confirm whether the port number is correct
  • Check the firewall settings

Connection Timeout

  • Check the network connection
  • Increase the timeout
  • Confirm whether the server address is correct

Incomplete Data Reception

  • Ensure both parties use the same protocol
  • Check whether the buffer size is sufficient
  • Consider using delimiters or fixed-length messages

Practical Application Scenarios

Socket programming has a wide range of applications in practice:

  • Instant messaging applications (such as WeChat, QQ)
  • Online games
  • Remote control software
  • File transfer tools
  • IoT device communication

Best Practices

  1. Always handle IO exceptions
  2. Use try-with-resources to ensure resource release
  3. Set reasonable timeouts for important operations
  4. Consider using a thread pool to handle multiple connections
  5. Design a clear communication protocol
Other Extensions