c# - 事件驱动的 TCP 客户端

标签 c# events tcp client

我想要一个事件驱动的、windows、c#、tcp 客户端。

当读取缓冲区中至少有 35 个字节时,我希望调用一个处理程序来读取这 35 个字节,从该“数据包”中获取一个长度值,然后对第二个长度的数据进行阻塞读取.

最佳答案

有一个相对较新的项目基本上提供了这个:https://github.com/clariuslabs/reactivesockets

从他们的页面:

Implements a very easy to use sockets API based on IObservable. It allows very simple protocol implementations such as:

var client = new ReactiveClient("127.0.0.1", 1055);

// The parsing of messages is done in a simple Rx query over the receiver observable
// Note this protocol has a fixed header part containing the payload message length
// And the message payload itself. Bytes are consumed from the client.Receiver 
// automatically so its behavior is intuitive.
IObservable<string> messages = from header in client.Receiver.Buffer(4)
                               let length = BitConverter.ToInt32(header.ToArray(), 0)
                               let body = client.Receiver.Take(length)
                               select Encoding.UTF8.GetString(body.ToEnumerable().ToArray());

// Finally, we subscribe on a background thread to process messages when they are available
messages.SubscribeOn(TaskPoolScheduler.Default).Subscribe(message => Console.WriteLine(message));
client.ConnectAsync().Wait();

关于c# - 事件驱动的 TCP 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11751542/

相关文章:

c# - 使用C#,当MySql Server上发生数据库更改时触发事件

azure - Azure IoT Hub的多个接收器,如何设置Azure函数的Epoch值?

c# - 在 TCP 期间发送断点会影响结果

Ruby 套接字性能特点

c# - 如何读取/写入/修改大型 Excel XLSB/XLSM 文件? (C#)

c# - 变量的 = 和 => 有什么区别?

wpf - 手动输入日期时 DatePickerSelectedDateChanged 事件发生两次

javascript - 谷歌分析事件跟踪不起作用

c# - 即使有异常(exception)规则,Windows 防火墙也会阻止 tcp 端口

c# - 在 C# 和 VB.NET 中自动转换为字符串