Java 和 Python 之间的 Socket 通信

code 服务码,根据code调用相应服务

status 状态码,根据执行结果返回状态码

socket之间使用json字符串通信

Java socket客户端与Python socket服务端

Java socket客户端

package com.brewin.hammer.system.util.socket;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
/**   
 * Java socket客户端  
 * @author Brewin 
 * @date 2020年5月20日 上午11:27:04   
 *   
 */
public class SocketClient {
    // 服务端IP地址
    public static final String HOST = "127.0.0.1";
    // 服务端端口
    public static final int PORT = 50001;

    public static void main(String args[]) throws Exception {

        // 发送给服务端的参数
        Map<String, String> paramMap = new HashMap<String, String>();
        //图片转换服务
        paramMap.put("code", "100");
        paramMap.put("url", "C:/Users/Brewin/Pictures/avatar/1.jpg");
        // map转成json字符串,需要引入fastjson依赖
        String param = JSON.toJSONString(paramMap);

        // 接收服务端返回的信息
        String socketServerMsg = getSocketServerMsg(HOST, PORT, param);
        System.out.println("服务端信息:" + socketServerMsg);
        // json字符串转成map,需要引入fastjson依赖
        Map resultMap = (Map) JSON.parse(socketServerMsg);
//        for (Object map : resultMap.entrySet()) {
//            System.out.println(((Map.Entry) map).getKey() + ":" + ((Map.Entry) map).getValue());
//        }

        String code=String.valueOf(resultMap.get("code"));
        System.out.println("服务码  : "+code);
        int status=(int) resultMap.get("status");
        System.out.println("状态码  : "+status);
        switch (code) {
            //图片转换服务
            case "100":
                System.out.println("图片转换服务");
                switch (status) {
                //成功
                case 10:
                    System.out.println("执行成功");
                    break;
                //失败
                case 20:
                    System.out.println("执行失败");
                    break;
                //默认
                default:
                    System.out.println("默认执行");
            }
                break;
            //数据库备份服务
            case "200":
                System.out.println("数据库备份服务");
                switch (status) {
                //成功
                case 10:
                    System.out.println("执行成功");
                    break;
                //失败
                case 20:
                    System.out.println("执行失败");
                    break;
                //默认
                default:
                    System.out.println("默认执行");
            }
                break;
            default:
                System.out.println("无对应服务");

        }
    }

    public static String getSocketServerMsg(String host, int port, String message) throws Exception {
        // 与服务端建立连接
        Socket socket = new Socket(host, port);
        // 获得输出流
        OutputStream outputStream = socket.getOutputStream();
        PrintWriter pWriter = new PrintWriter(outputStream);
        pWriter.write(message);
        pWriter.flush();
        // 通过shutdownOutput高速服务器已经发送完数据,后续只能接受数据
        socket.shutdownOutput();
        // 获得输入流
        InputStream inputStream = socket.getInputStream();

        byte[] bytes = new byte[1024];
        int len;
        StringBuilder sb = new StringBuilder();
        while ((len = inputStream.read(bytes)) != -1) {
            // 注意指定编码格式,发送方和接收方一定要统一,建议使用UTF-8
            sb.append(new String(bytes, 0, len, "UTF-8"));
        }
        inputStream.close();
        outputStream.close();
        socket.close();

        return sb.toString();
    }

}

Python socket服务端

from socket import *
import json
import random
HOST = '127.0.0.1'
PORT = 50000
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpServerSock = socket(AF_INET,SOCK_STREAM)
tcpServerSock.bind(ADDR)
tcpServerSock.listen(5)
while True:
    print('等待连接')
    tcpClientSock, addr = tcpServerSock.accept()
    print('接收到来自 :', addr,' 的连接')
    while True:
        request_data = tcpClientSock.recv(BUFSIZ)
        if not request_data:
            break
        request_data_str = str(request_data, 'UTF-8')
        print("来自客户端的数据:" +request_data_str)
        # 字符串转换成对象
        data = json.loads(request_data_str)

        response_data = {}
        response_data['code'] = data['code']
        response_data['status'] = 20
        # 图片转换服务
        if data['code']=='100':
            if random.randint(0, 900)<300:
                response_data['status'] = 10
                response_data['url'] = 'C:/Users/Brewin/Pictures/avatar/3.jpg'
            elif random.randint(0, 900)<600:
                response_data['status'] = 20
            else:
                response_data['status'] = 0

        # 数据存储服务
        elif data['code']=='200':
            if random.randint(0, 900) < 300:
                response_data['status'] = 10
                response_data['url'] = 'C:/Users/Brewin/Pictures/avatar/3.jpg'
            elif random.randint(0, 900) < 600:
                response_data['status'] = 20
            else:
                response_data['status'] = 0
        # 无对应服务
        else:
            response_data['code'] = '000'
            response_data['status'] = 10


        # 对象转换成字符串
        response_data_str=json.dumps(response_data)
    tcpClientSock.send(bytes(response_data_str, encoding = "utf8"))
    tcpClientSock.close()
tcpServerSock.close()

Java socket服务端与Python socket客户端

Java socket服务端

package com.brewin.hammer.system.util.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**   
 * Java socket服务端   
 * @author Brewin 
 * @date 2020年5月20日 上午11:08:32   
 *   
 */
public class SocketServer {
    // 服务端端口
    public static final int PORT = 50001;
    public static void main(String[] args) {
        try {
            //初始化服务端socket
            ServerSocket server = new ServerSocket(PORT);
            System.out.println("Java socket服务端开启!");
            //阻塞等待, 直到一个客户端 socket过来
            Socket socket = server.accept(); 
            System.out.println("有客户端socket连接!");
            //输入,接收来自客户端socket的数据
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream())); 
            //输出,传输数据至 客户端socket
            PrintWriter out = new PrintWriter(socket.getOutputStream()); 
            // 打印 客户 socket 发过来的字符,按行(\n,\r,或\r\n)
            System.out.println(in.readLine()); 
            // to 客户端,输出
            out.println("{\"code\": \"100\", \"status\": 10, \"url\": \"C:/Users/Brewin/Pictures/avatar/3.jpg\"}"); 
            out.flush(); 
            socket.close();
            server.close();
            System.out.println("服务结束!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Python socket客户端

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

python json字符串与对象之间的转换

# json字符串转换成对象
json2object = json.loads(json)

# 对象转换成json字符串
object2json=json.dumps(object)

Java json字符串与map之间的转换

// json字符串转成map,需要引入fastjson依赖
Map json2map = (Map) JSON.parse(json);

// map转成json字符串,需要引入fastjson依赖
String map2json = JSON.toJSONString(map);
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!