Csharp WebSocket Tutorial and Reference Guide

Author

Reads 856

A laptop displaying an analytics dashboard with real-time data tracking and analysis tools.
Credit: pexels.com, A laptop displaying an analytics dashboard with real-time data tracking and analysis tools.

C# provides a built-in WebSocket class in the System.Net.WebSockets namespace, which allows developers to create WebSocket connections.

This class is part of the .NET Framework and is available in .NET Core 3.0 and later versions.

To use the WebSocket class, you'll need to import the System.Net.WebSockets namespace at the top of your C# code file.

The WebSocket class provides several key methods, including ConnectAsync, SendAsync, and CloseAsync, which are essential for establishing and managing WebSocket connections.

These methods are asynchronous, meaning they don't block the calling thread, allowing for more efficient and scalable code.

A unique perspective: Websocket Close Code

Setting Up

To set up WebSockets in C#, you must create a .NET solution that handles client and server-side interactions. This involves setting up an ASP.NET Core 8 server to accept WebSocket connections and a primary C# client to test it.

You can start by creating a new ASP.NET Core Web API project in Visual Studio and adding middleware to handle WebSocket connections. This is done by modifying the Program.cs file to add support for WebSockets using app.UseWebSockets().

Related reading: Asp.net Websocket Example

Install

Futuristic workspace featuring a glowing computer screen with coding displayed, ideal for technology and programming concepts.
Credit: pexels.com, Futuristic workspace featuring a glowing computer screen with coding displayed, ideal for technology and programming concepts.

To get started with setting up WebSockets in C#, you'll first need to install the necessary packages. You can do this by adding the websocket-sharp package to your project using the NuGet Package Manager. Simply run the following command in the Package Manager Console: websocket-sharp.

Related reading: Websocket Sharp

Http Authentication

HTTP Authentication is supported by websocket-sharp, allowing you to set a pair of user name and password for the HTTP authentication using the WebSocket.SetCredentials method before connecting.

You should set a pair of user name and password for the HTTP authentication, as this is required for the connection to be established.

If you set preAuth to true, the client will send the credentials for the Basic authentication in the first handshake request to the server.

The server should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting the connection.

You can choose to provide Digest authentication by setting the necessary parameters.

Worth a look: Websockets vs Sse

Credit: youtube.com, HTTP Basic Authentication explained | HTTP authentication for client/server to server communication

As a client, you can choose to send the credentials in the first handshake request or wait for the server's response before sending them in the second request.

The choice of sending credentials in the first or second request depends on the value of the preAuth parameter.

You can set the proxy server URL and, if necessary, a pair of user name and password for the proxy server authentication using the WebSocket.SetProxy method before connecting.

Practical Considerations

When setting up, consider the time of day and the lighting in the space. Natural light can make a big difference in how a room feels.

The size of the space will also impact your setup. For example, a large room may require more furniture and decorations to fill the space.

Don't forget to measure the space before buying any furniture or decorations to ensure they fit. This will save you from having to return items.

A smiling adult man using a desktop computer at a desk, creating a positive work environment.
Credit: pexels.com, A smiling adult man using a desktop computer at a desk, creating a positive work environment.

In a small space, consider multi-functional furniture to save space and reduce clutter. This can be especially helpful in a studio apartment or office.

Make sure to have a clear path through the space for easy movement. This is especially important in a home office or workspace.

In a home office, consider the ergonomics of your workspace to avoid discomfort and injury. For example, keep your computer monitor at eye level and your keyboard at a comfortable height.

Server Implementation

To implement a WebSocket server in C#, you can use the WebSocketSharp.Server namespace, which provides the WebSocketBehavior and WebSocketServer classes. You can create a class that inherits from WebSocketBehavior to define the behavior of your WebSocket service.

When creating a new instance of the WebSocketServer class, you can add WebSocket services using the AddWebSocketService method, which requires a type that inherits from WebSocketBehavior and has a public parameterless constructor. The type of TBehavior must inherit the WebSocketBehavior class and must have a public parameterless constructor.

To manage multiple clients and their WebSocket instances, you can use a Dictionary to track each connected client and generate a unique ID for every new WebSocket connection. This allows for bidirectional communication and enables real-time updates between clients.

Recommended read: When to Use Websockets

Build

Credit: youtube.com, How to Build First MCP Server from Scratch | Model Context Protocol Hands-On Tutorial

websocket-sharp is built as a single assembly, websocket-sharp.dll. This makes it easy to include in your project.

Developing websocket-sharp is done with MonoDevelop. This is a simple way to build the project, just open websocket-sharp.sln and run build for the websocket-sharp project with any of the build configurations, such as Debug.

Implementing a Server

To implement a WebSocket server, you can create a class that inherits from the WebSocketBehavior class. This class will define the behavior of your WebSocket service, allowing you to handle incoming messages and events.

You can override the OnMessage method to handle incoming messages from clients, and the OnOpen, OnError, and OnClose methods to handle corresponding events.

The WebSocketBehavior.Send method can be used to send data to a specific client, while the Sessions property can be used to get a list of all connected clients.

To create a new instance of the WebSocketServer class, you can use the AddWebSocketService method, which takes the type of the WebSocket service and its absolute path as parameters.

Discover more: Websocket Service

Credit: youtube.com, Build and Ship Any MCP Server in MINUTES (Full Guide)

You can also use the HttpServer class to create an HTTP server that supports WebSockets.

To implement a robust WebSocket server that can handle multiple clients, you can use a Dictionary to track each connected client and their WebSocket instances.

You can use a mechanism like generating a unique ID (clientId) for every new WebSocket connection to track clients.

The HandleClientCommunication method can be used to listen to messages from a specific client and handle them accordingly.

Each message received from one client can be broadcasted to all connected clients, creating a basic chat server.

You should maintain a clean and error-tolerant server state by using try-catch blocks and ensuring that each client is removed from the list when disconnected.

By using the WebSocketSharp.Server.HttpServer class, you can create an HTTP server that accepts WebSocket handshake requests.

You can use the AddWebSocketService method to add any WebSocket service to your HttpServer with the specified behavior and path to the service.

To implement a WebSocket server that can manage multiple connections, you'll need a mechanism to keep track of each connected client and their WebSocket instances.

You might like: Websocket Use Cases

Credit: youtube.com, Building an MCP server in 2 minutes....

You can use a Dictionary to track each connected client and their WebSocket instances, and generate a unique ID (clientId) for every new WebSocket connection.

The HandleClientCommunication method can be used to listen to messages from a specific client and handle them accordingly, and each message received from one client can be broadcasted to all connected clients.

When creating a new instance of the WebSocketServer class, it's necessary to run it with root permission if you don't specify a port number, as it will set the port number to 80.

You can use the WebSocketBehavior.Sessions.Broadcast method to send data to every client in the service.

By implementing a robust WebSocket server, you can enable real-time communication between clients, which can be useful for applications like real-time chat, multiplayer games, and live data updates.

You can use the System.Net.WebSockets namespace to create a WebSocket server in C#.

The above server creates an instance of HttpListener and listens on the "http://localhost:8080/" URL.

When a client connects, it checks if the request is a WebSocket request, and if so, it accepts the WebSocket connection and starts a new task to handle the socket.

The task uses a loop to wait for messages from the client and sends a response back to the client.

You can handle the connection and message sending/receiving based on your needs.

Secure Connection

Hands typing code on a laptop in a workspace. Indoor setting focused on software development.
Credit: pexels.com, Hands typing code on a laptop in a workspace. Indoor setting focused on software development.

To ensure a secure connection, you can use the WebSocket class with a wss scheme WebSocket URL. This is especially important when dealing with sensitive information.

You can create a new instance of the WebSocket class with a wss scheme WebSocket URL to establish a secure connection. This is a crucial step in maintaining the integrity of your WebSocket server.

If you want to set a custom validation for the server certificate, you can use the WebSocket.SslConfiguration.ServerCertificateValidationCallback property. This allows you to specify a callback function that will be used to validate the server certificate.

The default callback always returns true, so if you don't set a custom validation, the connection will still be established. However, this may not be desirable in a production environment.

To create a secure connection as a WebSocket server, you can use the WebSocketServer or HttpServer class with settings for the secure connection. This will ensure that all connections to your server are encrypted and secure.

Intriguing read: Wss Websocket

Connecting Through HTTP Proxy Server

Credit: youtube.com, HTTP proxy server application implementation

You can connect to a WebSocket server through an HTTP proxy server using the WebSocket.SetProxy method.

To do this, you need to set the proxy server URL, which is a required parameter. This is done by passing the proxy server URL to the WebSocket.SetProxy method.

The proxy server URL should be in the format of a string, which is a type of data that can be used to represent text.

You may also need to provide a pair of user name and password for the proxy server authentication, which can be done using the Basic or Digest authentication methods.

Take a look at this: Websocket Proxy

Properties

In a well-implemented server, properties play a crucial role in managing the WebSocket connection.

The CloseStatus property indicates the reason why the remote endpoint initiated the close handshake. This is an essential piece of information for debugging and troubleshooting purposes.

The CloseStatusDescription property allows the remote endpoint to describe the reason why the connection was closed. This can be a helpful feature for understanding the cause of a connection closure.

From above crop anonymous male programmer in black hoodie working on software code on contemporary netbook and typing on keyboard in workspace
Credit: pexels.com, From above crop anonymous male programmer in black hoodie working on software code on contemporary netbook and typing on keyboard in workspace

The DefaultKeepAliveInterval property gets the default WebSocket protocol keep-alive interval. This interval is used to send periodic messages to the remote endpoint to keep the connection alive.

The State property returns the current state of the WebSocket connection, which can be used to determine whether the connection is open, closing, or closed.

The SubProtocol property gets the subprotocol that was negotiated during the opening handshake. This is an important property for applications that rely on specific subprotocols for communication.

Here are the properties of a WebSocket connection:

Client Implementation

To implement a WebSocket client in C#, you'll need to use the ClientWebSocket class from the System.Net.WebSockets namespace. This class allows for straightforward client connections, sending, and receiving messages.

The process of setting up a basic console application as a client is remarkably simple. Instantiate the ClientWebSocket, connect to the WebSocket server, and send a message. For example, you can connect to a server running locally on port 5000 at the /ws endpoint.

In a loop, the client listens for messages from the server, shutting down gracefully if the server decides to close the connection. This behavior is helpful for scenarios like a chat room where the client needs to be continuously engaged.

You might like: Client Websocket C#

Implementing a Client

Digital monitor with World map and COVID 19 statistical data of global confirmed cases
Credit: pexels.com, Digital monitor with World map and COVID 19 statistical data of global confirmed cases

To create a WebSocket client in C#, you'll need to use the ClientWebSocket class from the System.Net.WebSockets namespace. This class is a key component that allows you to connect and interact with the server, sending and receiving messages.

The process of creating a basic console application as a client is remarkably straightforward. Instantiate the ClientWebSocket, connect to the WebSocket server, and send a simple message. This is exactly what we'll do in our example.

You can use the ClientWebSocket API to handle all typical WebSocket activities, such as sending, receiving, and closing connections. The API is designed to be easy to use, allowing you to focus on implementing your client logic.

To expand the client, you can wrap the sending logic in a method that takes user input from the console. This will empower the client to send multiple messages to the server, enhancing the dynamism of the interaction.

Here are the basic steps to implement a client:

  • Instantiate the ClientWebSocket class
  • Connect to the WebSocket server
  • Send a message to the server
  • Listen for messages from the server

By following these steps, you'll be able to create a basic WebSocket client in C#. You can then expand the client to send messages based on user input, allowing the client to behave like a chat participant.

Remarks

HTML and CSS code on a computer monitor, highlighting web development and programming.
Credit: pexels.com, HTML and CSS code on a computer monitor, highlighting web development and programming.

Some classes in the System.Net.WebSockets namespace are supported on Windows 7, Windows Vista SP2, and Windows Server 2008.

However, the only public implementations of client and server WebSockets are supported on Windows 8 and Windows Server 2012.

Abstract classes in the System.Net.WebSockets namespace that are supported on Windows 7, Windows Vista SP2, and Windows Server 2008 allow developers to inherit and extend them with an actual implementation of client WebSockets.

Exactly one send and one receive is supported on each WebSocket object in parallel.

Issuing multiple sends or multiple receives at the same time will result in undefined behavior.

Ensure that the previous operation is awaited or completed before issuing the next one.

Advanced Features

WebSockets offer advanced features that make them a go-to solution for modern networked applications, especially for real-time communication systems.

The WebSocket protocol operates differently from traditional HTTP, starting with an initial HTTP handshake to upgrade the connection, and once this handshake is complete, communication switches to a persistent WebSocket connection.

Credit: youtube.com, Making A WebSocket Server With .NET 8🧑‍💻

This persistence makes WebSockets particularly effective for real-time applications, as it eliminates the overhead of setting up new connections for each interaction.

The ability to handle different message types—text, binary, and control frames—is an empowering feature in WebSockets.

You can identify the message type and act accordingly, making your server more versatile.

Handling different message types requires managing client groups effectively, which gives you a sense of control over your system.

To manage client groups, you can maintain a dictionary of client groups containing a list of WebSocket connections.

You can add clients to different groups and broadcast messages to specific groups, making your server capable of handling more complex communication patterns like chat rooms or gaming lobbies.

WebSocket compression is another advanced feature that can improve data transfer efficiency, especially when dealing with large payloads.

The WebSocketDeflateOptions in ASP.NET Core lets you enable per-message compression, which can save bandwidth in environments with limited bandwidth.

However, be sure to test your specific use case to determine if compression offers a net benefit, considering the processing overhead required to compress and decompress messages.

Credit: youtube.com, 7.5 How to Create a WebSocket Server in C# - Fun with WebSockets!

Handling idle connections intelligently is crucial to conserve resources, as WebSocket connections are persistent by nature and keeping unused connections open can lead to resource exhaustion.

You can use periodic ping-pong messages to check if the client is still active and, if not, close the connection to free up server resources.

See what others are reading: Webrtc Websocket Connections

Debugging and Testing

Debugging and testing are crucial steps in any C# WebSocket project. They help you identify and fix errors, ensuring your application runs smoothly.

To start debugging, you can use Visual Studio's built-in debugging tools, such as breakpoints and the debugger. This allows you to step through your code and examine variables in real-time.

A good debugging strategy involves isolating the problem area, as shown in the example where a WebSocket connection issue was resolved by checking the connection establishment process. This helps you focus on the root cause of the issue.

When testing WebSockets, you should consider using a WebSocket client library to simulate connections and send messages. This can be seen in the example where a WebSocket client was used to test a WebSocket server.

Credit: youtube.com, [Debug: FM WebSocket] Connection Test

Testing for WebSocket errors is also essential, as shown in the example where a try-catch block was used to handle exceptions and errors. This helps ensure your application remains stable and secure.

By following these debugging and testing strategies, you can ensure your C# WebSocket project is robust, reliable, and efficient.

See what others are reading: Websocket Load Testing

Protocol Details

The WebSocket protocol is framed-based, meaning data is transmitted as discrete frames that can carry either text or binary data, allowing for flexible communication depending on the application’s needs.

Each frame includes control information, such as message fragmentation or connection termination, which allows WebSocket to handle a high traffic volume with minimal performance impact.

The WebSocket protocol starts with an HTTP handshake initiated by the client, requesting an upgrade to the WebSocket protocol, and once the server acknowledges and accepts the request, the protocol switches to WebSocket, and the connection becomes persistent.

This ability to maintain a persistent connection eliminates the need for multiple HTTP requests and significantly reduces the overhead of traditional polling mechanisms.

You might like: Websocket Protocol

Credit: youtube.com, How to Set a Custom Sec-WebSocket-Protocol with C# ClientWebSocket

In .NET, support for the WebSocket protocol is integrated, providing developers with robust tools to implement WebSocket-based communication both on the server and client sides using the System.Net.WebSockets namespace.

The WebSocket protocol operates differently from traditional HTTP by starting with an initial HTTP handshake to upgrade the connection, which allows continuous data flow between the client and server.

This persistence makes WebSockets particularly effective for real-time applications, as it eliminates the overhead of setting up new connections for each interaction, making it ideal for scenarios that require real-time data transfer, such as chat applications, live streaming, and interactive gaming.

You might enjoy: Sec Websocket Protocol

Real-Time Connection

WebSockets enable bi-directional, real-time communication between clients and servers over the web.

This allows a browser or other client to establish a connection to a server and maintain that connection open for real-time communication.

A WebSocket server can be written in C# using the System.Net.WebSockets namespace.

The server creates an instance of HttpListener and listens on the "http://localhost:8080/" URL.

Credit: youtube.com, Building Real-Time Applications With SignalR & .NET 9 (full tutorial)

When a client connects, the server checks if the request is a WebSocket request, and if so, it accepts the WebSocket connection.

A new task is started to handle the socket, which uses a loop to wait for messages from the client and sends a response back to the client.

Please note that the above code is just an example, and you need to handle the connection and message sending/receiving based on your needs.

Real-time connections can be useful for applications such as real-time chat, multiplayer games, and live data updates.

This type of connection can provide a seamless user experience by allowing for instant updates and interactions.

Protocol Mechanics

The WebSocket protocol operates differently from traditional HTTP by starting with an initial HTTP handshake to upgrade the connection. This handshake is initiated by the client, requesting an upgrade to the WebSocket protocol.

The client and server can send and receive messages independently, making the communication model asynchronous and highly efficient. This ability to maintain a persistent connection eliminates the need for multiple HTTP requests and significantly reduces the overhead of traditional polling mechanisms.

Additional reading: Websocket vs Http

Credit: youtube.com, 7.1 Introduction to WebSockets in C# - Fun with WebSockets!

Data is transmitted as discrete frames, which can carry either text or binary data. These frames include control information, such as message fragmentation or connection termination.

The WebSocket protocol is framed-based, allowing for flexible communication depending on the application's needs. This lightweight structure allows WebSocket to handle a high traffic volume with minimal performance impact.

The client and server's ability to initiate data transfers whenever needed makes WebSockets ideal for dynamic interactions, such as chat systems and online multiplayer games.

Jeannie Larson

Senior Assigning Editor

Jeannie Larson is a seasoned Assigning Editor with a keen eye for compelling content. With a passion for storytelling, she has curated articles on a wide range of topics, from technology to lifestyle. Jeannie's expertise lies in assigning and editing articles that resonate with diverse audiences.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.