c# webeocket client访问127.0.0.1的9960端口,怎么写
时间: 2024-10-20 12:14:12 浏览: 21
在C#中,如果你想要使用WebSocket客户端连接到本地127.0.0.1的9960端口,你可以使用`System.Net.WebSockets.ClientWebSocket`类。下面是一个简单的示例代码片段:
```csharp
using System;
using System.Net.WebSockets;
class Program
{
static async Task Main(string[] args)
{
// 创建WebSocket连接的选项
var uri = new Uri("ws://127.0.0.1:9960");
// 使用ClientWebSocket创建连接
using (var socket = new ClientWebSocket())
{
try
{
await socket.ConnectAsync(uri, CancellationToken.None);
// 发送数据
string message = "Hello from C# WebSocket client!";
var bytes = Encoding.UTF8.GetBytes(message);
await socket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None);
// 接收数据并处理
var result = await socket.ReceiveAsync(new ArraySegment<byte>(ArrayPool<byte>.Shared.Rent(1024)), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
Console.WriteLine($"Connection closed with code {result.CloseStatus} and reason {result.CloseStatusDescription}");
else
Console.WriteLine($"Received message: {Encoding.UTF8.GetString(result.Array, 0, result.Count)}");
// 关闭连接
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing connection", CancellationToken.None);
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
}
}
}
```
这个程序首先创建一个到指定IP和端口的WebSocket连接,然后发送一条消息并接收响应。请注意,实际运行此代码需要安装`System.Net.WebSockets`命名空间。
阅读全文