SoFunction
Updated on 2025-04-05

Detailed explanation of Socket programming usage methods in Java

Preface

Socket programming is a very important part of network communication. It allows data transmission between different devices. In Java, Socket programming mainly usespackage to implement. In this article, we will explore in detail the Socket programming in Java, including the basic concepts of Socket, how to use Socket in Java, and simple communication examples between clients and servers.

1. Basic knowledge of Socket

1. What is Socket?

Sockets are the endpoints of network communications that allow data exchange between two computers over the network. Socket is an indispensable part of network programming. It is built on the TCP/IP protocol to manage connections and transmit data.

Simply put, Socket is used to handle the following two operations:

  • Client Socket: Used to connect to remote servers.
  • Server Socket: Used to listen to client requests and establish a connection with them.

2. How Socket works

The communication process of Socket can be understood as the following steps:

  • Server side:passServerSocketThe class creates a Socket that listens for a specific port, waiting for the client to connect.
  • Client:passSocketClass connects to the server's IP and port.
  • Data transmission: After the connection is established, both parties read and write data through the input/output stream.
  • Close the connection: After the communication is over, both parties close the Socket to release the resources.

2. Basic classes of Socket in Java

In Java, Socket programming mainly relies on the following classes:

  • ServerSocket: Used to listen to client's connection requests on the server side.
  • Socket: Used to communicate on the client and server side.
  • InputStream/OutputStream: Used for reading and writing data.

1. ServerSocket class

ServerSocketFor server side, it listens to client's connection requests on a specific port, waiting for the connection to be established. Common methods are:

  • accept(): Wait and accept client connection.
  • close(): Close the server-side socket.

2. Socket class

SocketClass is used for client to connect to servers and perform data transmission. Common methods are:

  • getInputStream(): Get the input stream and read the data from it.
  • getOutputStream(): Get the output stream, used to send data to the other party.
  • close(): Close the Socket connection.

3. Simple client-server example

Next, we use a simple example to demonstrate how to implement Socket communication using Java.

1. Server-side code

import .*;
import ;
import ;

public class SimpleServer {
    public static void main(String[] args) {
        try {
            // Create a server socket with 8888 listening port            ServerSocket serverSocket = new ServerSocket(8888);
            ("The server has been started, waiting for the client to connect...");

            // Wait for client connection            Socket socket = ();
            ("Client connected:" + ().getHostAddress());

            // Get the input stream and read the data sent by the client            BufferedReader reader = new BufferedReader(new InputStreamReader(()));
            String clientMessage = ();
            ("Received client message:" + clientMessage);

            // Get the output stream and send data to the client            PrintWriter writer = new PrintWriter((), true);
            ("Hello, client!");

            // Close the resource            ();
            ();
            ();
            ();
        } catch (IOException e) {
            ();
        }
    }
}

2. Client code

import .*;
import ;

public class SimpleClient {
    public static void main(String[] args) {
        try {
            // Connect to the server            Socket socket = new Socket("localhost", 8888);
            ("Connected to the server");

            // Get the output stream and send data to the server            PrintWriter writer = new PrintWriter((), true);
            ("Hello, server!");

            // Get the input stream and read the data returned by the server            BufferedReader reader = new BufferedReader(new InputStreamReader(()));
            String serverMessage = ();
            ("Received the server message:" + serverMessage);

            // Close the resource            ();
            ();
            ();
        } catch (IOException e) {
            ();
        }
    }
}

3. Run steps

  • Start the server-side program and the server will start listening to port 8888.
  • Start the client program, and the client will connect to the server and send a message.
  • After receiving the client's message, the server will respond to a message and close the connection.
  • After the client receives the server's response message, it also closes the connection.

4. Output example

  • Server-side output
The server is started,Waiting for client connection...
Client is connected:127.0.0.1
Received a client message:Hello,server!
  • Client output
Connected to the server
Received a server message:Hello,Client!

4. Frequently Asked Questions in Socket Programming

1. Port occupancy issues

When programming Socket, if a port has been occupied, createServerSocketWill be thrown whenBindException. At this time, you need to check whether the port has been used by other processes. You can replace the port or end the conflicting process.

2. Data reading problem

In useBufferedReaderOr other streams read data, it usually occurs when blocking until the data sent by the other party contains a newline or the stream is closed. Therefore, usePrintWriterPay attention to calling when sending dataprintln(), notprint()

3. Timeout problem

By default, Socket'saccept()andread()The method is blocking. If you need to set the timeout, you can usesetSoTimeout(int timeout)Method to avoid long-term blocking of the program.

5. Summary

Socket programming in Java passesServerSocketandSocketClasses can easily implement communication between clients and servers. In actual development, Socket programming is usually used to build the foundation of the underlying network protocol. Through the examples in this article, you should have a basic understanding of Socket programming in Java. According to actual project requirements, the code can be further optimized, multi-threaded support can be added, and complex scenarios such as concurrent client connections can be handled.

This is the end of this article about Socket programming usage in Java. For more related Socket programming content in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!