c#

C#中如何使用WebSocket进行通信

小樊
244
2024-09-06 06:07:37
栏目: 编程语言

在C#中,你可以使用System.Net.WebSockets命名空间中的类来实现WebSocket通信

  1. 首先,确保你的项目已经引用了System.Net.WebSockets

  2. 创建一个WebSocket客户端:

using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace WebSocketClientExample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            await ConnectToWebSocketServer();
        }

        private static async Task ConnectToWebSocketServer()
        {
            using var client = new ClientWebSocket();
            Uri uri = new Uri("wss://example.com/websocket"); // 替换为你的WebSocket服务器地址

            try
            {
                await client.ConnectAsync(uri, CancellationToken.None);
                Console.WriteLine("Connected to WebSocket server.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error connecting to WebSocket server: {ex.Message}");
                return;
            }

            // 发送消息
            string message = "Hello, WebSocket!";
            byte[] buffer = Encoding.UTF8.GetBytes(message);
            await client.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);

            // 接收消息
            byte[] receiveBuffer = new byte[1024];
            WebSocketReceiveResult result = await client.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
            string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, result.Count);
            Console.WriteLine($"Received message: {receivedMessage}");

            // 关闭连接
            await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye", CancellationToken.None);
        }
    }
}
  1. 运行客户端程序,它将连接到指定的WebSocket服务器,发送一条消息并接收服务器的响应。

注意:这个示例仅用于演示目的,实际应用中你可能需要处理更复杂的场景,例如错误处理、心跳检测等。此外,你还可以考虑使用第三方库,如Microsoft.AspNetCore.Http.Abstractions,它提供了更高级的功能和更好的性能。

0
看了该问题的人还看了