C#如何应用webSocket 开发一个中型项目
时间: 2023-12-14 12:39:04 浏览: 216
使用C#开发WebSocket项目可以分为以下几个步骤:
1. 创建WebSocket服务端
使用.NET的WebSocket类库来创建WebSocket服务端。可以在Visual Studio中创建一个新的C#控制台应用程序,并添加WebSocket类库的引用。在代码中创建一个WebSocketServer对象,然后通过监听本地端口来接受连接请求。
```csharp
using System;
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();
while (true)
{
var context = await listener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
var webSocketContext = await context.AcceptWebSocketAsync(null);
await HandleWebSocket(webSocketContext.WebSocket);
}
else
{
context.Response.StatusCode = 400;
context.Response.Close();
}
}
}
static async Task HandleWebSocket(WebSocket webSocket)
{
var buffer = new byte[1024];
while (webSocket.State == WebSocketState.Open)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
else if (result.MessageType == WebSocketMessageType.Text)
{
var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received Message: {message}");
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
}
}
}
}
}
```
2. 创建WebSocket客户端
同样地,使用.NET的WebSocket类库来创建WebSocket客户端。在代码中创建一个WebSocket对象,然后通过连接到服务端来建立连接。可以使用SendAsync方法向服务端发送消息,使用ReceiveAsync方法接收服务端发送的消息。
```csharp
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketClient
{
class Program
{
static async Task Main(string[] args)
{
var client = new ClientWebSocket();
await client.ConnectAsync(new Uri("ws://localhost:8080/"), CancellationToken.None);
while (true)
{
var message = Console.ReadLine();
var buffer = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
buffer = new byte[1024];
var result = await client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
var response = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received Message: {response}");
}
}
}
}
```
3. 实现业务逻辑
在WebSocket服务端和客户端中添加具体的业务逻辑,例如实现聊天室、游戏等功能。
以上是使用C#开发WebSocket项目的基本流程,具体实现需要根据具体的业务需求进行调整。
阅读全文