用c#写一段websocket
时间: 2023-07-18 17:34:17 浏览: 147
C# websocket
4星 · 用户满意度95%
以下是一个简单的C# WebSocket程序,用于建立WebSocket连接并发送和接收消息:
```csharp
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketProgram
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("WebSocket Program\n");
// WebSocket endpoint
Console.Write("Enter WebSocket endpoint: ");
Uri uri = new Uri(Console.ReadLine());
// Create client WebSocket
ClientWebSocket clientWebSocket = new ClientWebSocket();
await clientWebSocket.ConnectAsync(uri, CancellationToken.None);
// Send message
Console.Write("\nEnter message to send: ");
string message = Console.ReadLine();
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
await clientWebSocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, CancellationToken.None);
// Receive message
byte[] buffer = new byte[1024];
WebSocketReceiveResult result = await clientWebSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
string receivedMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine("\nReceived message: " + receivedMessage);
// Close WebSocket
await clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing connection", CancellationToken.None);
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
}
}
```
该程序要求输入WebSocket端点,然后创建客户端WebSocket并连接到端点。它还要求输入要发送的消息,并将其作为UTF8编码的字节数组发送到服务器。然后,它接收来自服务器的消息,并将其作为UTF8编码的字符串打印出来。最后,该程序关闭WebSocket连接。注意:该程序只是一个简单的示例,实际的WebSocket程序需要更多的功能和异常处理。
阅读全文