java python communication

java python communication

一般有两种:socket 和 pipe。

参考了这个链接:http://jj09.net/interprocess-communication-python-java/

先说pipe

from java to python

java file:

import java.io.*;

public class MyClass2 {
	public static void main(String[] args) throws InterruptedException{
		System.out.println("First msg");
		System.out.println("Second msg");
		System.out.println("x");
	}
}

python file:

#!/usr/bin/python

import subprocess

p = subprocess.Popen(["java", "MyClass2"], stdout=subprocess.PIPE)
line = p.stdout.readline()
while(line != "x\n"):
	print line
	line = p.stdout.readline()

from python to java

java file:

import java.io.*;

public class MyClass {
	public static void main(String[] args) {
		try {
			BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
			PrintWriter writer = new PrintWriter("result.txt", "UTF-8");
			String s = bufferRead.readLine();
			while(s.equals("x")==false) {
				writer.println(s);
				s = bufferRead.readLine();
			}
			writer.close();
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
}

python file:

#!/usr/bin/python

import subprocess

p = subprocess.Popen(["java", "MyClass"], stdin=subprocess.PIPE)
p.stdin.write("First line\r\n")
p.stdin.write("Second line\r\n")
p.stdin.write("x\r\n") # this line will not be printed into the file

再说socket

from java to python

java client file:

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.PrintWriter;  
import java.net.Socket;  
import java.net.UnknownHostException;  
  
public class TestSocketClient {  
  
    public static void main(String[] args) {  
        try {  
            Socket socket = new Socket("127.0.0.1", 5000);  
            System.out.println("Client start!");  
            PrintWriter out = new PrintWriter(socket.getOutputStream()); // 输出,to 服务器 socket  
            BufferedReader in = new BufferedReader(new InputStreamReader(  
                    socket.getInputStream())); // 输入, from 服务器 socket  
            out.println("Client request! 🙂 ");  
            out.flush(); // 刷缓冲输出,to 服务器  
            System.out.println(in.readLine()); // 打印服务器发过来的字符串  
            System.out.println("Client end!");  
            socket.close();  
        } catch (UnknownHostException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
  
    }  
  
}  

python server file:

import socket
HOST = '127.0.0.1'
PORT = 5000

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
sock.send("232132132131".encode())

szBuf = sock.recv(1024)
byt = 'recv:' + szBuf.decode('utf-8')
print(byt)

sock.close()

from python to java

java server file:

import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.io.PrintWriter;  
import java.net.ServerSocket;  
import java.net.Socket;  
  
public class DataSocketServer {  
  
    public static void main(String[] args) {  
        try {  
            ServerSocket server = new ServerSocket(5000);  
            System.out.println("Server start!");  
            Socket socket = server.accept(); //阻塞等待, 直到一个客户端 socket过来  
            System.out.println("There comes a socket!");  
            BufferedReader in = new BufferedReader(new InputStreamReader(  
                    socket.getInputStream())); //输入,from 客户端  
            PrintWriter out = new PrintWriter(socket.getOutputStream()); //输出,to 客户端  
            System.out.println(in.readLine());  // 打印 客户 socket 发过来的字符,按行(\n,\r,或\r\n)  
            out.println("Server reponse! ^_^ ");   
            out.flush(); // to 客户端,输出  
            socket.close();  
            server.close();  
            System.out.println("Server end!");  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
  
}  

python client file:

import socket     
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     
sock.connect(('localhost',5000))  
print('Client start!')  
sock.send(bytes('客户端:)\n',encoding='utf-8'))   # str 类型 -> bytes 类型,发送,\n 千万不要少了,因为前面的 server 是按行读取的  
print(str(sock.recv(1024),encoding = 'utf-8'))    # bytes 类型 -> str 类型,接受  
sock.close()   
print('Client end!')  

发表评论

电子邮件地址不会被公开。 必填项已用*标注