C# 使用 WebSocket与Python进行JSON信息通信

本文介绍了一种使用C#作为客户端、Python作为服务器的WebSocket通信方案。C#端通过WebSocketSharp插件发送JSON序列化的消息到Python服务器,后者使用websockets库接收并解析这些消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C# 端

为了让数据的传输更加稳定,采取的策略是用Python当作websocket服务器C#端当作客户端来进行。

C# 上需要安装上WebSocketSharp插件


// See https://aka.ms/new-console-template for more information
using System;
using WebSocketSharp;
using System.Text.Json;
namespace WebSocket_Demo
{
    class Program
    {
        
        private static void Main(string[] args)
        {
            Console.WriteLine("Websocket Demo");
            WebSocket web = new WebSocket("ws://127.0.0.1:7890");
            web.OnMessage += Web_OnMessage;
            web.Connect();
            Student_info student_demo = new Student_info();
            student_demo.studentName = "小毛";
            student_demo.id = 181000000;
            student_demo.score = 91;
            
            web.Send(JsonSerializer.Serialize(student_demo));
            
            Console.ReadKey();
            web.Close();
            //Console.ReadLine();
            
            
        }

        private static void Web_OnMessage(object? sender, MessageEventArgs e)
        {
            Console.WriteLine("Received a message of " + e.ToString());
        }
    }

    class Student_info
    {
        public string studentName { get; set; }
        public int id { get; set; }
        public int score { get; set; }
        
    }
}

Python 代码

Python 主要是写一个websocket的server

import websockets
import asyncio
import json
global data
PORT = 7890
print("Running on PORT 7890")
async def echo(websocket,path):
    global data
    id = 0
    print("A client just connected")
    async for message in websocket:
        data = json.loads(message)
        print(data)

start_server = websockets.serve(echo,"127.0.0.1",PORT)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

测试效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值