Home  >  Article  >  Java  >  How does Java network programming communicate between the server and the client?

How does Java network programming communicate between the server and the client?

PHPz
PHPzOriginal
2024-04-15 13:06:01992browse

In Java network programming, the server and client communicate through the client-server model. Follow the following steps: Create the server: Use ServerSocket to listen on the port and wait for the client to connect. Handle the client request: accept the connection and read data from the client, process the request and return the response, and finally close the client socket. Create a client: establish a Socket connection, send a request to the server, read the response and close the socket.

How does Java network programming communicate between the server and the client?

Java network programming: server-side and client communication

In Java network programming, between the server and the client The communication follows the client-server model. This article will delve into how the server side and client side establish a connection and exchange data through sockets.

Create the server side

The server side is responsible for listening to client connections and processing requests from clients. In order to create a server side, you can use the following steps:

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

public class Server {

    public static void main(String[] args) throws IOException {
        // 创建一个服务器套接字,监听端口 8080
        ServerSocket serverSocket = new ServerSocket(8080);

        // 循环等待客户端连接
        while (true) {
            // 接受客户端连接并返回一个套接字
            Socket clientSocket = serverSocket.accept();

            // 处理客户端请求
            handleClientRequest(clientSocket);

            // 关闭客户端套接字
            clientSocket.close();
        }

        // 关闭服务器套接字
        serverSocket.close();
    }

    public static void handleClientRequest(Socket clientSocket) throws IOException {
        // 从输入流读取客户端数据
        InputStream inputStream = clientSocket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String request = reader.readLine();

        // 处理请求并返回响应
        String response = processRequest(request);

        // 向输出流写入响应
        OutputStream outputStream = clientSocket.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream);
        writer.println(response);
    }
}

Create Client

The client is responsible for connecting to the server side and sending requests. The following steps are used to create a client:

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

public class Client {

    public static void main(String[] args) throws IOException {
        // 创建一个客户端套接字并连接到服务器端(主机名:localhost,端口:8080)
        Socket clientSocket = new Socket("localhost", 8080);

        // 向服务器端发送请求
        OutputStream outputStream = clientSocket.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream);
        writer.println("Hello from client!");

        // 从服务器端读取响应
        InputStream inputStream = clientSocket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String response = reader.readLine();
        System.out.println("Response from server: " + response);

        // 关闭客户端套接字
        clientSocket.close();
    }
}

Practical case

The following is a practical case that demonstrates how to use Java network programming between the server and the client Communicate between:

Server-side code:

// Server.java
import java.net.*;
import java.io.*;

public class Server {

    public static void main(String[] args) throws IOException {
        // 监听端口 8080
        ServerSocket serverSocket = new ServerSocket(8080);

        // 等待客户端连接
        Socket clientSocket = serverSocket.accept();

        // 读取客户端数据
        BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String request = reader.readLine();
        System.out.println("Received request: " + request);

        // 响应客户端请求
        PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
        writer.println("Hello from server!");
        writer.flush();

        // 关闭套接字
        clientSocket.close();
        serverSocket.close();
    }
}

Client-side code:

// Client.java
import java.net.*;
import java.io.*;

public class Client {

    public static void main(String[] args) throws IOException {
        // 连接到服务器端(主机名:localhost,端口:8080)
        Socket clientSocket = new Socket("localhost", 8080);

        // 向服务器端发送数据
        PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
        writer.println("Hello from client!");
        writer.flush();

        // 读取服务器端响应
        BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String response = reader.readLine();
        System.out.println("Received response: " + response);

        // 关闭套接字
        clientSocket.close();
    }
}

After running this code, the server The client will listen for connections on port 8080, and the client will connect to the server and send a "Hello from client!" message. The server will receive the message and respond with "Hello from server!".

The above is the detailed content of How does Java network programming communicate between the server and the client?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn