Java Socket programming is the basis of network communication, and data exchange between clients and servers is realized through Socket. 1. Socket in Java is divided into the Socket class used by the client and the ServerSocket class used by the server; 2. When writing a Socket program, you must first start the server listening port, and then initiate the connection by the client; 3. The communication process includes connection establishment, data reading and writing, and stream closure; 4. Notes include avoiding port conflicts, correctly configuring IP addresses, reasonably closing resources, and supporting multiple clients. Mastering these can realize basic network communication functions.
In Java network programming, Socket is one of the most basic and important parts. It allows communication between two programs over the network, both local LAN and the Internet. This article mainly talks about the basic concepts of Socket programming in Java and a simple example to help you get started quickly.

What is Java Socket?
In Java, Socket is a mechanism used to establish connections and exchange data between different devices in the network. Java provides java.net
package to support network communication, two core classes are:

-
Socket
: used for client, indicating a connection to the server. -
ServerSocket
: used to listen to client requests and establish connections.
Simply put, Socket is like a telephone, the client dials (connects), the server answers (accepts connections), and then both parties can talk (transmits data).
How to write a simple Java Socket program?
Let’s use a classic example of “client send messages, server reply” to illustrate the entire process.

Step 1: Start the server
The server needs to be started first and wait for the client to connect. You can use ServerSocket
to listen for a port.
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(12345)) { System.out.println("The server has started, waiting for connection..."); Socket socket = serverSocket.accept(); // Block until a client connects System.out.println("Client connected"); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); String clientMessage = in.readLine(); System.out.println("Received:" clientMessage); out.println("The server receives your message: "clientMessage); } catch (IOException e) { e.printStackTrace(); } } }
Step 2: Run the client
The client creates a Socket
instance and connects to the server IP and port.
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("Response:" response); } catch (IOException e) { e.printStackTrace(); } } }
Although this example is simple, it covers the core steps of Socket programming: connecting, reading and writing data.
Frequently Asked Questions and Precautions
- Port occupied : If the specified port number has been occupied by other programs, the server will not be started. You can try changing the port number, such as between 1024 and 65535.
- IP address configuration error : Make sure the client is connected to the correct IP address. If it is a native test, use
localhost
or127.0.0.1
. - Stream closing order : Be sure to remember to close the input and output streams and Socket connections, otherwise resource leakage may occur.
- Multithreading process multiple clients : The above example can only handle one client. If you want to handle multiple connections at the same time, you need to use multi-threading or NIO.
- Protocol design : In actual development, it is recommended to define your own communication protocol, such as transmitting structured data in JSON format.
Let's summarize
Java Socket programming is not difficult, the key is to understand how the client/server model works. After mastering the basic connection and data reading and writing processes, more complex functions can be expanded on this basis, such as file transfer, real-time chat, etc. Basically all that is it, just try it out.
The above is the detailed content of Java Socket Programming Fundamentals and Examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Lazy loading only queries when accessing associations can easily lead to N 1 problems, which is suitable for scenarios where the associated data is not determined whether it is needed; 2. Emergency loading uses with() to load associated data in advance to avoid N 1 queries, which is suitable for batch processing scenarios; 3. Emergency loading should be used to optimize performance, and N 1 problems can be detected through tools such as LaravelDebugbar, and the $with attribute of the model is carefully used to avoid unnecessary performance overhead.

Laravel supports the use of native SQL queries, but parameter binding should be preferred to ensure safety; 1. Use DB::select() to execute SELECT queries with parameter binding to prevent SQL injection; 2. Use DB::update() to perform UPDATE operations and return the number of rows affected; 3. Use DB::insert() to insert data; 4. Use DB::delete() to delete data; 5. Use DB::statement() to execute SQL statements without result sets such as CREATE, ALTER, etc.; 6. It is recommended to use whereRaw, selectRaw and other methods in QueryBuilder to combine native expressions to improve security

JWT is an open standard for safe transmission of information. In Java, authentication and authorization can be achieved through the JJWT library. 1. Add JJWT API, Impl and Jackson dependencies; 2. Create JwtUtil tool class to generate, parse and verify tokens; 3. Write JwtFilter intercepts requests and verify BearerTokens in Authorization header; 4. Register Filter in SpringBoot to protect the specified path; 5. Provide a login interface to return JWT after verifying the user; 6. The protected interface obtains user identity and roles through parsing the token for access control, and ultimately realizes a stateless and extensible security mechanism, suitable for distributed systems.

Go generics are supported since 1.18 and are used to write generic code for type-safe. 1. The generic function PrintSlice[Tany](s[]T) can print slices of any type, such as []int or []string. 2. Through type constraint Number limits T to numeric types such as int and float, Sum[TNumber](slice[]T)T safe summation is realized. 3. The generic structure typeBox[Tany]struct{ValueT} can encapsulate any type value and be used with the NewBox[Tany](vT)*Box[T] constructor. 4. Add Set(vT) and Get()T methods to Box[T] without

json.loads() is used to parse JSON strings into Python data structures. 1. The input must be a string wrapped in double quotes and the boolean value is true/false; 2. Supports automatic conversion of null→None, object→dict, array→list, etc.; 3. It is often used to process JSON strings returned by API. For example, response_string can be directly accessed after parsing by json.loads(). When using it, you must ensure that the JSON format is correct, otherwise an exception will be thrown.

Use regular expression capture group in Notepad to effectively reorganize text. First, you need to open the replacement dialog box (Ctrl H), select "Search Mode" as "regular expression", 1. Use () to define the capture group, such as (\w ) to capture words; 2. Use \1 and \2 to reference the corresponding group in the replacement box; 3. Example: Exchange the name "JohnDoe" as "Doe, John", find (\w )\s (\w ), replace it with \2,\1; 4. Date format conversion 2023-12-25 to 25/12/2023, find (\d{4})-(\d{2})-(\d{2}), replace it with \3/\2/\1; 5. Log reordering can extract time, level, ID and other information

Advanced Java interview questions mainly examine the understanding of JVM internal mechanisms, concurrent programming, performance tuning, design patterns and system architecture. 1. The Java memory model (JMM) defines the visibility, atomicity and order of memory operations between threads. The volatile keyword and happens-before rules ensure correct synchronization to avoid the problem of update invisibility caused by CPU cache. G1GC is suitable for large heaps and predictable pause scenarios. Areas with a lot of garbage are preferred through area recycling. ZGC uses shading pointers and loading barriers to achieve submillisecond-level pauses, and the pause time is independent of the heap size, which is suitable for low-latency systems. 2. Use ConcurrentHashMap to design thread-safe LRU cache

Python's ternary operator is used to concisely implement if-else judgment, and its syntax is "value_if_trueif conditionelsevalue_if_false"; 1. It can be used for simple assignment, such as returning the corresponding string based on positive and negative values; 2. It can avoid division errors, such as determining that the denominator is non-zero and then division; 3. It can select content according to conditions in string format; 4. It can assign labels to different elements in list derivation formula; it should be noted that this operator is only suitable for binary branches and should not be nested multiple layers. Complex logic should use the traditional if-elif-else structure to ensure readability.
