Skip to content

Instantly share code, notes, and snippets.

@num8er
Created April 3, 2024 03:59
Show Gist options
  • Save num8er/039688f76226756d1ae25fd4d8a83bb6 to your computer and use it in GitHub Desktop.
Save num8er/039688f76226756d1ae25fd4d8a83bb6 to your computer and use it in GitHub Desktop.
C# WebSocketEventEmitter
using System;
class Program
{
static async Task Main(string[] args)
{
var webSocketEventEmitter = new WebSocketEventEmitter();
webSocketEventEmitter.MessageReceived += (sender, message) =>
{
Console.WriteLine("Received message: " + message);
};
webSocketEventEmitter.ErrorOccurred += (sender, errorMessage) =>
{
Console.WriteLine("Error occurred: " + errorMessage);
};
Uri serverUri = new Uri("wss://echo.websocket.org");
await webSocketEventEmitter.ConnectAsync(serverUri);
// Sending a message
await webSocketEventEmitter.SendAsync("Hello, WebSocket!");
// Wait for user input to close the connection
Console.WriteLine("Press any key to disconnect...");
Console.ReadKey();
await webSocketEventEmitter.DisconnectAsync();
}
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class WebSocketEventEmitter
{
private ClientWebSocket clientWebSocket;
private CancellationTokenSource cancellationTokenSource;
// Define events
public event EventHandler<string> MessageReceived;
public event EventHandler<string> ErrorOccurred;
// Constructor
public WebSocketEventEmitter()
{
clientWebSocket = new ClientWebSocket();
cancellationTokenSource = new CancellationTokenSource();
}
// Connect to the WebSocket server
public async Task ConnectAsync(Uri uri)
{
try
{
await clientWebSocket.ConnectAsync(uri, cancellationTokenSource.Token);
await ReceiveLoop();
}
catch (Exception ex)
{
OnErrorOccurred(ex.Message);
}
}
// Send message over WebSocket
public async Task SendAsync(string message)
{
if (clientWebSocket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));
await clientWebSocket.SendAsync(buffer, WebSocketMessageType.Text, true, cancellationTokenSource.Token);
}
}
// Receive loop to continuously listen for incoming messages
private async Task ReceiveLoop()
{
while (clientWebSocket.State == WebSocketState.Open)
{
try
{
var buffer = new ArraySegment<byte>(new byte[4096]);
WebSocketReceiveResult result = await clientWebSocket.ReceiveAsync(buffer, cancellationTokenSource.Token);
if (result.MessageType == WebSocketMessageType.Text)
{
string receivedMessage = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
OnMessageReceived(receivedMessage);
}
else if (result.MessageType == WebSocketMessageType.Close)
{
await clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", cancellationTokenSource.Token);
}
}
catch (Exception ex)
{
OnErrorOccurred(ex.Message);
}
}
}
// Trigger MessageReceived event
protected virtual void OnMessageReceived(string message)
{
MessageReceived?.Invoke(this, message);
}
// Trigger ErrorOccurred event
protected virtual void OnErrorOccurred(string errorMessage)
{
ErrorOccurred?.Invoke(this, errorMessage);
}
// Disconnect from WebSocket
public async Task DisconnectAsync()
{
cancellationTokenSource.Cancel();
if (clientWebSocket.State == WebSocketState.Open)
{
await clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
clientWebSocket.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment