溫馨提示×

java socket編程怎樣實(shí)現(xiàn)遠(yuǎn)程通信

小樊
82
2024-10-12 17:38:20
欄目: 編程語言

在Java中,使用Socket編程實(shí)現(xiàn)遠(yuǎn)程通信主要包括兩個(gè)步驟:創(chuàng)建客戶端(Client)和服務(wù)器端(Server)。下面是一個(gè)簡單的示例,展示了如何使用Java Socket編程實(shí)現(xiàn)客戶端和服務(wù)器之間的通信。

  1. 創(chuàng)建服務(wù)器端(Server):
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));
        String message = reader.readLine();
        System.out.println("Received message: " + message);

        OutputStream outputStream = socket.getOutputStream();
        PrintWriter writer = new PrintWriter(outputStream, true);
        writer.println("Hello from server!");

        socket.close();
        serverSocket.close();
    }
}
  1. 創(chuàng)建客戶端(Client):
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);
        writer.println("Hello from client!");

        InputStream inputStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String message = reader.readLine();
        System.out.println("Received message: " + message);

        socket.close();
    }
}

在這個(gè)示例中,服務(wù)器端監(jiān)聽指定端口(12345),當(dāng)客戶端連接到服務(wù)器時(shí),服務(wù)器會(huì)讀取客戶端發(fā)送的消息,并向客戶端發(fā)送一條消息??蛻舳诉B接到服務(wù)器后,會(huì)向服務(wù)器發(fā)送一條消息,并接收服務(wù)器返回的消息。

要運(yùn)行這個(gè)示例,請首先運(yùn)行Server類,然后運(yùn)行Client類。你會(huì)看到客戶端和服務(wù)器之間的通信輸出。

這只是一個(gè)簡單的示例,實(shí)際應(yīng)用中可能需要考慮更多因素,例如多線程處理并發(fā)連接、異常處理、加密通信等。

0