C# websocket客户端
时间: 2024-01-09 09:23:26 浏览: 148
以下是一个C# WebSocket客户端的示例代码:
```csharp
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
public class WebSocketClient
{
private ClientWebSocket clientWebSocket;
public async Task Connect(string url)
{
clientWebSocket = new ClientWebSocket();
await clientWebSocket.ConnectAsync(new Uri(url), CancellationToken.None);
Console.WriteLine("连接成功");
await Receive();
}
public async Task Send(string message)
{
if (clientWebSocket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes(message));
await clientWebSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None);
}
}
private async Task Receive()
{
var buffer = new byte[1024];
while (clientWebSocket.State == WebSocketState.Open)
{
var result = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
var receivedMessage = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine("接收到消息:" + receivedMessage);
}
}
}
}
```
使用示例:
```csharp
WebSocketClient myWSClient = new WebSocketClient();
await myWSClient.Connect("ws://127.0.0.1:7789/ws");
await myWSClient.Send("Hello, server!");
```
请注意,以上示例代码仅为演示目的,实际使用时可能需要根据具体情况进行适当修改。
阅读全文