How do I set up a C# websocket server?
The method of building a WebSocket server in C# is achieved by using the WebSocket class and related namespaces.
Here is a simple example:
- Firstly, make sure your project references the System.Net.WebSockets namespace.
- Create a class for a WebSocket server and initialize a WebSocket object within it. For example:
using System;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
public class MyWebSocketServer
{
private HttpListener _httpListener;
private CancellationTokenSource _cts;
public MyWebSocketServer(string url)
{
_httpListener = new HttpListener();
_httpListener.Prefixes.Add(url);
_cts = new CancellationTokenSource();
}
public async Task Start()
{
_httpListener.Start();
Console.WriteLine("WebSocket server started.");
while (!_cts.Token.IsCancellationRequested)
{
HttpListenerContext context = await _httpListener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
ProcessWebSocketRequest(context);
}
else
{
// Handle non-WebSocket request
context.Response.StatusCode = 400;
context.Response.Close();
}
}
}
private async void ProcessWebSocketRequest(HttpListenerContext context)
{
HttpListenerWebSocketContext webSocketContext = null;
try
{
webSocketContext = await context.AcceptWebSocketAsync(subProtocol: null);
Console.WriteLine("WebSocket connection established.");
await HandleWebSocketConnection(webSocketContext.WebSocket);
}
catch (Exception ex)
{
Console.WriteLine("WebSocket connection failed: " + ex.Message);
if (webSocketContext != null)
{
webSocketContext.WebSocket.CloseAsync(WebSocketCloseStatus.InternalServerError, "Internal Server Error", CancellationToken.None);
}
}
}
private async Task HandleWebSocketConnection(WebSocket webSocket)
{
byte[] buffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
// Handle received data
string receivedMessage = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine("Received: " + receivedMessage);
// Echo the received message back to the client
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), WebSocketMessageType.Text, true, CancellationToken.None);
// Get next message
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
Console.WriteLine("WebSocket connection closed.");
}
public void Stop()
{
_cts.Cancel();
_httpListener.Stop();
_httpListener.Close();
}
}
- Create an instance of MyWebSocketServer at the entry point of the program and start the server. For example:
class Program
{
static async Task Main(string[] args)
{
string url = "http://localhost:8080/";
MyWebSocketServer server = new MyWebSocketServer(url);
await server.Start();
Console.WriteLine("Press any key to stop the server.");
Console.ReadKey();
server.Stop();
}
}
The code above sets up a basic WebSocket server, which listens on a specified URL, and handles incoming WebSocket connections and messages. Feel free to customize and expand it according to your needs.