(转)netcore原生websocket客户端写法(ClientWebSocket)
2024-09-01 13:19:57
代码:
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Demo
{
class Program
{
async static Task Main(string[] args)
{
var client = new ClientWebSocket();
client.ConnectAsync(new Uri("ws://echo.websocket.org"), CancellationToken.None).Wait();
StartReceiving(client);
string line;
while ((line = Console.ReadLine()) != "exit")
{
var array = new ArraySegment<byte>(Encoding.UTF8.GetBytes(line));
await client.SendAsync(array, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
static async void StartReceiving(ClientWebSocket client)
{
while (true)
{
var array = new byte[4096];
var result = await client.ReceiveAsync(new ArraySegment<byte>(array), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
string msg = Encoding.UTF8.GetString(array, 0, result.Count);
Console.ForegroundColor = ConsoleColor.DarkBlue;
Console.WriteLine("--> {0}", msg);
Console.ForegroundColor = ConsoleColor.DarkGray;
}
}
}
}
}
最新文章
- 微软移动 Nokia Lumia SensorCore SDK 介绍及上手体验
- select标签非空验证,第一个option value=";";即可
- .net环境下从PDF文档中抽取Text文本的一些方法汇总
- passivedns 安装指南
- 改变select组件的option选中状态的快捷方法
- Container View Controller
- Jquery Ashx 存在缓存问题
- 【现代程序设计】【homework-02】【11061027】
- OSS.Common扩展.Net Standard支持实例分享
- python爬微信公众号前10篇历史文章(1)-思路概览
- Open Source BI Platform List
- php中获取用户登陆的IP地址以及常规处理
- Linux进程管理工具Supervisor
- 【算法习题】正整数数组中和为sum的任意个数的组合数
- Spring Boot WebSocket从入门到放弃
- FreeSWITCH 增删模组
- Analysis of FCN
- Java LinkedList源码剖析
- 洛谷 P4175: bzoj 1146: [CTSC2008]网络管理
- dvwa 源码分析(四) --- dvwaPhpIds.inc.php分析