针对“C# 实现WebSocket服务端教程”,我将提供完整的攻略。下面是详细的步骤:
步骤一:创建一个空的C#控制台应用程序
可以使用Visual Studio进行创建,也可以使用命令行创建,此处不再赘述。在创建时,需要选择.NET Core 3.x
或者.NET 5+
作为Target Framework。
步骤二:添加NuGet包
在控制台中输入以下命令,添加System.Net.WebSockets
NuGet包:
dotnet add package System.Net.WebSockets
步骤三:实现WebSocketServer
在应用程序的根目录下,创建WebSocketServer.cs
文件,实现WebSocket服务端的代码。以下是一个很简单的示例:
using System;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketServerDemo
{
public class WebSocketServer
{
private readonly HttpListener httpListener;
private readonly CancellationTokenSource cts = new CancellationTokenSource();
public WebSocketServer(string[] prefixes)
{
httpListener = new HttpListener();
foreach (var prefix in prefixes)
{
httpListener.Prefixes.Add(prefix);
}
}
public async Task StartAsync()
{
httpListener.Start();
Console.WriteLine("WebSocket server started.");
while (!cts.Token.IsCancellationRequested)
{
var listenerContext = await httpListener.GetContextAsync();
if (listenerContext.Request.IsWebSocketRequest)
{
var webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol: null);
await HandleWebSocketRequestAsync(webSocketContext.WebSocket);
}
else
{
listenerContext.Response.StatusCode = 400;
listenerContext.Response.Close();
}
}
}
private async Task HandleWebSocketRequestAsync(WebSocket webSocket)
{
var buffer = new byte[1024];
var receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cts.Token);
while (!receiveResult.CloseStatus.HasValue)
{
var message = Encoding.UTF8.GetString(buffer, 0, receiveResult.Count);
Console.WriteLine($"Received message: {message}");
var response = Encoding.UTF8.GetBytes($"[Echo] {message}");
await webSocket.SendAsync(new ArraySegment<byte>(response, 0, response.Length), WebSocketMessageType.Text, true, CancellationToken.None);
receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cts.Token);
}
await webSocket.CloseAsync(receiveResult.CloseStatus.Value, receiveResult.CloseStatusDescription, CancellationToken.None);
}
public void Stop()
{
cts.Cancel();
httpListener.Stop();
}
}
}
步骤四:启动WebSocket服务端
在Program.cs
文件中,编写启动WebSocket服务端的代码。以下是示例代码:
using System;
using System.Threading.Tasks;
namespace WebSocketServerDemo
{
class Program
{
static async Task Main(string[] args)
{
var server = new WebSocketServer(new[] { "http://localhost:8000/" });
await server.StartAsync();
}
}
}
这将启动一个WebSocket服务端,监听在http://localhost:8000/
地址。
示例一:使用JavaScript进行测试
如果WebSocket服务端启动成功,在浏览器中打开Html文件时就可以使用WebSocket发送消息,观察服务端是否正常接收。
以下是Html文件中示例的JavaScript代码:
const webSocket = new WebSocket('ws://localhost:8000/');
webSocket.onopen = function (event) {
console.log('WebSocket is open now.');
}
webSocket.onmessage = function (event) {
console.log(`WebSocket received message: ${event.data}`);
}
webSocket.onerror = function (event) {
console.error('WebSocket error: ', event);
}
webSocket.onclose = function (event) {
console.log('WebSocket close: ', event);
}
webSocket.send('Hello, WebSocket!');
当JavaScript代码过程中调用了send
方法时,会向WebSocket服务端发送一条消息。
示例二:使用C# HttpClient进行测试
以下是通过C# HttpClient进行测试的代码:
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace WebSocketServerDemo
{
class Program
{
static async Task Main(string[] args)
{
var server = new WebSocketServer(new[] { "http://localhost:8000/" });
_ = server.StartAsync();
using (var httpClient = new HttpClient())
{
await httpClient.GetStringAsync("http://localhost:8000/");
using (var webSocketClient = new ClientWebSocket())
{
await webSocketClient.ConnectAsync(new Uri("ws://localhost:8000/"), default);
var buffer = new byte[1024];
var message = new ArraySegment<byte>(buffer);
foreach (var msg in new[] { "Hello, WebSocket!", "Are you there?" })
{
Console.WriteLine($"Send message: {msg}");
var messageSegment = new ArraySegment<byte>(Encoding.UTF8.GetBytes(msg));
await webSocketClient.SendAsync(messageSegment, WebSocketMessageType.Text, endOfMessage: true, CancellationToken.None);
var receiveResult = await webSocketClient.ReceiveAsync(message, CancellationToken.None);
var response = Encoding.UTF8.GetString(buffer, 0, receiveResult.Count);
Console.WriteLine($"Receive message: {response}");
}
await webSocketClient.CloseAsync(WebSocketCloseStatus.NormalClosure, "Close from WebSocketClient.", default);
}
}
server.Stop();
}
}
}
当代码过程中创建了一个ClientWebSocket
时,就可以使用其发送和接收WebSocket消息。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C# 实现WebSocket服务端教程 - Python技术站