c#(Visual studio)与python(pycharm)通信小demo

c#(Visual studio)与python(pycharm)通信小demo

做毕设需要使用机器学习的小伙伴们看过来,在做好前后端后,想把数据库里的数据传到一个单独的模块(机器学习模块)进行数据处理得出一个预测结果。这个小样使用http通讯协议,前端将数据打包为一个json,通过http协议发送post请求后将数据传到服务端(pycharm):

使用anaconda创建一个虚拟环境,只需要安装一个 HTTPServer包就行,安装命令

conda install HTTPServer

pycharm服务端代码:

from __future__ import print_function
from http.server import HTTPServer, BaseHTTPRequestHandler
import json

host = ('localhost', 19999)


class My_Server(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        data = {'result': 'OK'}
        # 发给请求客户端的响应数据
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def do_POST(self):
        self.send_response(200)
        datas = self.rfile.read(int(self.headers['content-length']))
        print('headers', self.headers)
        print("-->> post:", self.path, self.client_address)

        # 解析json数据
        data_str = str(datas, 'utf-8')
        date_json = json.loads(data_str)
        print(data_str)

        print(date_json['id'])
        print(date_json['name'])

        if date_json['id'] == '520':
            print('闫m')


        # 发给请求客户端的响应数据
        self.send_header('Content-type', 'application/json')
        # self.wfile.write(json.dumps(data).encode())

        # 解决跨域问题
        self.send_header("Access-Control-Allow-Origin", "*");
        self.end_headers()

        # 返回的数据
        result_json0 = {'result': 'MeToo',
                        }

        self.wfile.write(json.dumps(result_json0).encode())


class User_app:
    if __name__ == '__main__':
        server = HTTPServer(host, My_Server)
        print("server启动@ : %s:%s" % host)
        server.serve_forever()

服务端启动后会一直保持监听状态,接收客户端传递过来的信息。
在这里插入图片描述

VS客户端代码:

    //http协议post请求
    public static string post(string uri, string postData, string encoding = "utf-8")
    {
        string strBuff = string.Empty;
        byte[] byteArray = Encoding.GetEncoding(encoding).GetBytes(postData);
        try
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(uri));
            webRequest.Method = "post";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
            System.IO.Stream newStream = webRequest.GetRequestStream();
            newStream.Write(byteArray, 0, byteArray.Length);
            newStream.Close();
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            using (Stream respStream = response.GetResponseStream())
            {
                using (StreamReader respStreamReader = new StreamReader(respStream, Encoding.GetEncoding(encoding)))
                {
                    strBuff = respStreamReader.ReadToEnd();
                }
            }
            response.Close();

            webRequest.Abort();
        }
        catch (Exception ex)
        {
            strBuff = string.Empty;
        }
        return strBuff;
    }

在函数里调用post方法,将数据打包成json格式。

protected void button_Click(object sender, EventArgs e)
{
    string PostUrl = "http://localhost:19999/";
    string id = "520";
    string Name = "闫m";
    JObject patientinfo = new JObject();
    JArray ids = new JArray();
    ids.Add(id);
    patientinfo["id"] = ids;
    patientinfo["name"] = Name;
    string sendData = JsonConvert.SerializeObject(patientinfo);
    //eg:  发送Url需要的格式:sendData={"id":123,"name":小黑}
    //打印发送的数据
    Debug.WriteLine(sendData);
    //打印接收的数据
    Debug.WriteLine(post(PostUrl, sendData));
}

接收的数据
在这里插入图片描述
返回的数据
在这里插入图片描述
如果想要实现不同电脑间访问,需要在同一个局域网下(连同一个一个wifi)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

躺尸研究员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值