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)