基于Socket实现跨语言数据通信

要在Java和Python之间进行通信,您可以使用Socket。Socket是一种用于在网络上进行通信的技术。它允许两个应用程序在网络上发送和接收数据。

下面是一个简单的Java客户端和Python服务器示例,它们可以通过Socket进行通信。

Java客户端:

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

public class JavaClient {
    public static void main(String[] args) throws IOException {
        String hostName = "localhost";
        int portNumber = 1234;

        try (
            Socket socket = new Socket(hostName, portNumber);
            PrintWriter out =
                new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in =
                new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            BufferedReader stdIn =
                new BufferedReader(
                    new InputStreamReader(System.in))
        ) {
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                System.out.println("echo: " + in.readLine());
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                hostName);
            System.exit(1);
        }
    }
}

Python服务器:

import socket

HOST = 'localhost'
PORT = 1234

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

在这个例子中,Java客户端连接到Python服务器。当Java客户端发送一条消息时,Python服务器接收该消息并将其发送回客户端,Java客户端将消息输出到控制台。

这只是一个简单的示例,您可以在此基础上扩展和修改代码以满足您的具体需求。

你可能感兴趣的:(java,jvm,linux)