用c#和websocket做服务器端主动发消息给web客户端?
在C#中使用WebSocket实现服务器端向Web客户端主动发送消息,需要遵循以下步骤:
1. 创建WebSocket服务器
首先,你需要创建一个WebSocket服务器来接收客户端连接并处理消息。
csharpusing System;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class WebSocketServer
{
private HttpListener listener;
public WebSocketServer(string[] prefixes)
{
listener = new HttpListener();
foreach (string prefix in prefixes)
{
listener.Prefixes.Add(prefix);
}
}
public async Task Start()
{
listener.Start();
Console.WriteLine("Listening for connections...");
while (true)
{
HttpListenerContext context = await listener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
ProcessWebSocketRequest(context);
}
else
{
context.Response.StatusCode = 400;
context.Response.Close();
}
}
}
private async void ProcessWebSocketRequest(HttpListenerContext context)
{
WebSocketContext webSocketContext = null;
try
{
webSocketContext = await context.AcceptWebSocketAsync(null);
Console.WriteLine("WebSocket connection established.");
await HandleWebSocket(webSocketContext.WebSocket);
}
catch (Exception ex)
{
context.Response.StatusCode = 500;
context.Response.Close();
Console.WriteLine($"WebSocket error: {ex.Message}");
}
}
private async Task HandleWebSocket(WebSocket webSocket)
{
try
{
byte[] buffer = new byte[1024];
while (webSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
string clientMessage = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine($"Received from client: {clientMessage}");
// Echo back to client (for demonstration purposes)
byte[] responseBuffer = Encoding.UTF8.GetBytes($"Server received: {clientMessage}");
await webSocket.SendAsync(new ArraySegment<byte>(responseBuffer, 0, responseBuffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
}
else if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"WebSocket error: {ex.Message}");
}
finally
{
if (webSocket != null)
{
webSocket.Dispose();
}
}
}
public async Task Stop()
{
listener.Stop();
listener.Close();
await Task.CompletedTask;
}
}
2. 启动WebSocket服务器
csharpclass Program
{
static async Task Main(string[] args)
{
string[] prefixes = { "http://localhost:8080/" }; // Replace with your desired URL
WebSocketServer server = new WebSocketServer(prefixes);
await server.Start();
Console.WriteLine("Press any key to stop the server...");
Console.ReadKey();
await server.Stop();
}
}
3. Web客户端连接和消息处理
在Web客户端,你可以使用JavaScript来连接WebSocket并处理来自服务器的消息。
javascriptconst socket = new WebSocket('ws://localhost:8080/');
socket.onopen = function(event) {
console.log('WebSocket connected.');
};
socket.onmessage = function(event) {
console.log('Message from server:', event.data);
};
socket.onclose = function(event) {
console.log('WebSocket disconnected.');
};
// Example: Send message to server
function sendMessage(message) {
socket.send(message);
}
4. 服务器端主动发送消息给客户端
在C#中,可以在WebSocket处理程序中使用SendAsync
方法来主动向客户端发送消息。
csharp// Inside HandleWebSocket method
string messageToSend = "Hello from server!";
byte[] buffer = Encoding.UTF8.GetBytes(messageToSend);
await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
这样,服务器端就能够主动向连接的Web客户端发送消息了。记得处理WebSocket的连接状态和异常,以保证稳定的通信。