Java network programming can interact with applications written in other languages, such as Python. This article shows the steps for interaction between Java and Python: Java creates a server and listens on a specific port. Python creates a client that connects to the IP address and port of the Java server. Python sends data to Java, and Java processes and sends a response to Python.
Java network programming interacts with other languages
Java network programming can not only communicate with other Java applications; Language (such as Python) to interact with applications written in. This article will show how to use Java network programming to interact with Python and provide a practical case.
1. Create Java server
import java.net.ServerSocket; import java.net.Socket; import java.io.InputStream; import java.io.OutputStream; public class JavaServer { public static void main(String[] args) throws Exception { // 创建服务端套接字,监听端口 5000 ServerSocket serverSocket = new ServerSocket(5000); // 接受客户端连接,并创建套接字 Socket socket = serverSocket.accept(); // 获取输入流和输出流 InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); // 读取客户端发送的数据 byte[] buffer = new byte[1024]; int length = inputStream.read(buffer); String message = new String(buffer, 0, length); // 处理来自客户端的数据 // ... // 向客户端发送数据 String response = "已收到来自 Python 客户端的数据"; outputStream.write(response.getBytes()); // 关闭套接字和服务端套接字 socket.close(); serverSocket.close(); } }
2. Create Python client
import socket # 创建客户端套接字,连接到 Java 服务端的 IP 地址和端口 clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientSocket.connect(('127.0.0.1', 5000)) # 发送数据到 Java 服务端 message = "这是来自 Python 客户端的数据" clientSocket.send(message.encode()) # 接收来自 Java 服务端的数据 response = clientSocket.recv(1024) print(response.decode()) # 关闭客户端套接字 clientSocket.close()
Practical case: File transfer
The following code shows a practical case of file transfer implemented using Java and Python:
Java server side:
// ... 同 JavaServer 代码 ... // 接收文件内容 byte[] fileContent = new byte[1024]; int totalLength = 0; while ((length = inputStream.read(fileContent)) != -1) { totalLength += length; } // ... 同 JavaServer 代码 ...
Python client:
# ... 同 PythonClient 代码 ... with open('test.txt', 'rb') as f: fileContent = f.read() clientSocket.send(fileContent) # ... 同 PythonClient 代码 ...
The above is the detailed content of How does Java network programming interact with other languages such as Python?. For more information, please follow other related articles on the PHP Chinese website!