c# 创建一个WebSocketServer 项目
时间: 2023-07-20 20:20:02 浏览: 203
可以按照以下步骤创建一个 C# WebSocketServer 项目:
1. 创建一个新的 C# 控制台应用程序项目。
2. 添加 `System.Net.WebSockets` 命名空间。
3. 在 `Program.cs` 文件中添加以下代码:
```csharp
using System;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketServer
{
class Program
{
static async Task Main(string[] args)
{
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("Listening...");
while (true)
{
var context = await listener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
ProcessWebSocketRequest(context);
}
else
{
context.Response.StatusCode = 400;
context.Response.Close();
}
}
}
static async void ProcessWebSocketRequest(HttpListenerContext context)
{
try
{
var webSocket = await context.AcceptWebSocketAsync(subProtocol: null);
Console.WriteLine("WebSocket connected");
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result = null;
while (webSocket.State == WebSocketState.Open)
{
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
var message = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received message: {message}");
var responseBytes = System.Text.Encoding.UTF8.GetBytes($"Echo: {message}");
await webSocket.SendAsync(new ArraySegment<byte>(responseBytes), WebSocketMessageType.Text, true, CancellationToken.None);
}
else if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
Console.WriteLine("WebSocket closed");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"WebSocket error: {ex.Message}");
}
}
}
}
```
4. 运行程序,WebSocket 服务器将在 `http://localhost:8080/` 上监听连接请求。当客户端连接时,服务器将打印一条消息并开始接收客户端发送的消息。当接收到消息时,服务器将打印消息内容并将其回显给客户端。客户端可以通过发送 `Close` 消息来关闭 WebSocket 连接。
阅读全文