91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

before java網絡通信如何實現

小樊
83
2024-09-20 18:48:42
欄目: 編程語言

在Java中實現網絡通信,通常需要使用到Java套接字編程(Socket Programming)。套接字是一種用于實現不同計算機間或同一計算機內的進程間通信的技術。以下是一個簡單的Java網絡通信示例,展示了如何使用TCP協議進行客戶端和服務器之間的通信:

  1. 服務器端代碼(Server.java):
import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) throws IOException {
        int port = 12345;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("Server is listening on port " + port);

        Socket socket = serverSocket.accept();
        System.out.println("Client connected");

        InputStream inputStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        OutputStream outputStream = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream, true);

        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println("Received: " + line);
            writer.println("Server received: " + line);
        }

        socket.close();
        serverSocket.close();
    }
}
  1. 客戶端代碼(Client.java):
import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {
        String serverAddress = "localhost";
        int port = 12345;

        Socket socket = new Socket(serverAddress, port);
        System.out.println("Connected to server");

        OutputStream outputStream = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream, true);

        InputStream inputStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        String line;

        while (true) {
            System.out.print("Enter a message: ");
            line = console.readLine();
            if (line == null || line.equalsIgnoreCase("exit")) {
                break;
            }

            writer.println(line);
            System.out.println("Sent: " + line);

            String response = reader.readLine();
            System.out.println("Server response: " + response);
        }

        socket.close();
    }
}

首先運行服務器端代碼(Server.java),然后運行客戶端代碼(Client.java)。客戶端將連接到服務器并發送消息,服務器將接收消息并將其原樣返回。當客戶端輸入"exit"時,連接將關閉。

0
安庆市| 竹溪县| 汝城县| 观塘区| 永定县| 鱼台县| 新丰县| 乌兰浩特市| 牙克石市| 女性| 会同县| 宽城| 厦门市| 昌平区| 正安县| 二连浩特市| 收藏| 商水县| 台江县| 玉龙| 图们市| 潮州市| 牟定县| 连州市| 夹江县| 合山市| 松潘县| 灵宝市| 靖安县| 泊头市| 额敏县| 彭州市| 界首市| 博客| 安龙县| 上虞市| 泽州县| 尉犁县| 天门市| 长子县| 成武县|