C# send data via WebSocket as producer, python receive data via websocket as consumer
Producer
Install-Package Newtonsoft.Json Install-Package WebSocketSharp-netstandard using 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; } }

Consumer
python -m pip install websockets import asyncio import websockets import json from datetime import datetime async 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())


浙公网安备 33010602011771号