当前位置: 首页 > news >正文

C# send data via WebSocket as producer, python receive data via websocket as consumer

Producer

Install-Package Newtonsoft.Json
Install-Package WebSocketSharp-netstandardusing System;
using System.Threading;
using WebSocketSharp;
using WebSocketSharp.Server;
using Newtonsoft.Json;namespace ConsoleApp1
{internal class Program{static void Main(string[] args){Open_WebSocket();Console.ReadKey();}static void Open_WebSocket(){var wssv = new WebSocketServer("ws://localhost:8080");wssv.AddWebSocketService<BookDataServer>("/bookData");wssv.Start();if(wssv.IsListening){Console.WriteLine($"{DateTime.Now} the websocket is started,url:ws://localhost:8080/bookData");Console.WriteLine($"Press any key to quit.");Console.ReadKey();}wssv.Stop();Console.WriteLine($"{DateTime.Now},the websocketserver is stopped!");}}public class BookDataServer:WebSocketBehavior{System.Timers.Timer tmr;int idx = 0;protected override void OnOpen(){Console.WriteLine($"{DateTime.Now} BookDataServer started!");tmr=new System.Timers.Timer();tmr.Interval = 1000;tmr.Elapsed += Tmr_Elapsed;tmr.Start();}private void Tmr_Elapsed(object? sender, System.Timers.ElapsedEventArgs e){try{var temp_idx = Interlocked.Increment(ref idx);var bk = new Book{Id = temp_idx,Name=$"Name_{temp_idx}",Author=$"Author_{temp_idx}",ISBN=$"ISBN_{temp_idx}_{Guid.NewGuid():N}",Abstract=$"Abstract_{temp_idx}",Comment = $"Comment_{temp_idx}",Content = $"Content_{temp_idx}",Summary = $"Summary_{temp_idx}",Title = $"Title_{temp_idx}",Topic = $"Topic_{temp_idx}",CreateTime=DateTime.Now};var bk_json = JsonConvert.SerializeObject(bk, Formatting.Indented);Send(bk_json);Console.WriteLine($"{DateTime.Now},sent data:{bk_json}");}catch (Exception ex){Console.WriteLine($"{DateTime.Now},ex:{ex.Message}");}}protected override void OnClose(CloseEventArgs e){Console.WriteLine($"{DateTime.Now} the python client is closed!");tmr?.Dispose();}protected override void OnError(WebSocketSharp.ErrorEventArgs e){Console.WriteLine($"{DateTime.Now},{e.Message}");}}public class Book{public int Id { get; set; }public string Name { get; set; }public string ISBN { get; set; }public string Abstract { get; set; }public string Author { get; set; }public string Comment { get; set; }public string Content { get; set; }public string Summary { get;set; }public string Title { get; set; }public string Topic { get; set; }            public DateTime CreateTime { get; set; }=DateTime.Now;}
}

 

image

 

 

 

 

 

Consumer

python -m pip install websocketsimport asyncio
import websockets
import json
from datetime import datetimeasync def receive_book_data():uri="ws://localhost:8080/bookData"try:async with websockets.connect(uri) as websock:print(f'{datetime.now()},begin to receive data...')while True:data=await websock.recv()print(f'{datetime.now()}, received data:\n{data}')# dic=json.loads(data)# print(f"Id:{dic['Id']},Name:{dic['Name']},Author:{dic['Author']},ISBN:{dic['ISBN']},Abstract:{dic['Abstract']},Comment:{dic['Comment']},Content:{dic['Content']},Summary:{dic['Summary']},Title:{dic['Title']},Topic:{dic['Topic']},CreateTime:{dic['CreateTime']}")except websock.exceptions.ConnectionClosed:print(f'{datetime.now()} disclosed with C# websocketserver!')except Exception as ex:print(f'{datetime.now()},receive data error:{ex}')if __name__=="__main__":asyncio.run(receive_book_data())

 

 

image

 

http://www.jsqmd.com/news/362234/

相关文章:

  • B2B营销终极指南:定义认知、策略落地与趋势前瞻
  • 2026年AI选题工具推荐指南:如何利用4亿+文献索引,3分钟搞定开题报告? - 沁言学术
  • 模型「漂移」新范式,何恺明新作让生成模型无须迭代推理
  • 便携式测油仪采购指南:行业走势、性能、合规与售后服务全解析 - 品牌推荐大师1
  • 有没有开源的大文件上传JS库支持分片上传和断点续传?
  • Kubernetes HPA(Horizontal Pod Autoscaler)详解
  • 完整教程:【Java高级编程】集合框架和泛型
  • 2026年深圳美国本科留学中介哪家好?深度解析高端申请与定制规划的关键选择 - 品牌2025
  • 【毕业设计】基于springboot+小程序的24小时自助棋牌室小程序的设计与实现(源码+文档+远程调试,全bao定制等)
  • 新生儿纸尿裤买哪个?5大品牌核心维度实测对比,新手爸妈告别选择困难 - 速递信息
  • 2026年SAT备考攻略:针对藤校申请的优质补习机构推荐,助你轻松拿高分 - 品牌2025
  • openclaw安装飞书插件时报错 spawn
  • 2026年高通量自动化细胞培养推荐企业评测报告:高性能细胞培养设备/专业供应商/高品质系统公司选择指南 - 品牌推荐大师1
  • 双线备战2026:冲刺美港顶尖名校,高端定制中介如何破局? - 品牌2025
  • ‌A/B测试AI代理:多臂赌博机算法在流量分配策略的优化工具‌
  • 【效率神器】如何将 AIGC 生成的 LaTeX 公式完美粘贴到 WPS/Word?
  • 【毕业设计】基于springboot的智慧社区服务系统的设计与开发(源码+文档+远程调试,全bao定制等)
  • 深南电路高端PCB泰国工厂,12.74亿元换来的交付资格
  • 不同网段k8s节点notready问题处理
  • 【毕业设计】基于springboot的医院教学管理系统(源码+文档+远程调试,全bao定制等)
  • 脱产申请英美留学没经验?2026值得信赖的机构推荐 - 品牌2025
  • 2026陕西防腐木厂家排名:长廊/护栏/古建凉亭工程哪家强? - 深度智识库
  • 【计算机毕业设计案例】基于Java+springboot的医院教学培训考核医护人员管理系统(程序+文档+讲解+定制)
  • 在多阶段松弛实验中采用分布式光纤传感量化局部和非局部岩石变形
  • 图灵奖得主领衔,30多国100多位专家重磅《2026 国际人工智能安全报告》
  • 2026年SAT补习机构哪家好?我们从快速出分与高效提分角度为您推荐 - 品牌2025
  • 巅峰对决:最强模型GPT-5.3-Codex与Claude Opus 4.6同时发布
  • 2026陕西户外防腐木工程避坑指南!厂家权威推荐:聚焦长廊、护栏、古建凉亭 - 深度智识库
  • Fortran: Python实现UDF(User Defined Function)逻辑流程
  • 环境感知测试:图神经网络在容器网络拓扑的异常预测工具