WebSocket is a protocol that allows for real-time, full-duplex communication over a single, long-lived connection. It is widely used in web development to enable real-time communication between clients and servers. In this article, we will explore how to implement WebSocket communication in C#.
To get started with WebSocket in C, we need to use the System.Net.WebSockets
namespace, which provides classes and methods for working with the WebSocket protocol. The ClientWebSocket
class is used to create a WebSocket client, while the HttpListenerWebSocketContext
class is used to represent a WebSocket connection on the server side.
Here’s an example of how to create a WebSocket client in C:
using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
public class WebSocketClient
{
public static async Task Connect(string url)
{
using (ClientWebSocket client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(url), CancellationToken.None);
// Perform WebSocket communication here
await client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
}
}
In the above code, we create a ClientWebSocket
instance and connect to the specified URL using the ConnectAsync
method. We can then perform WebSocket communication operations within the using
block. Finally, we close the WebSocket connection using the CloseAsync
method.
Now let’s take a look at how to implement a WebSocket server in C. Here’s an example:
using System;
using System.Net;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
public class WebSocketServer
{
private HttpListener listener;
public async Task Start(string url)
{
listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();
while (true)
{
HttpListenerContext context = await listener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
HttpListenerWebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
// Handle WebSocket communication here
await HandleWebSocketCommunication(webSocketContext.WebSocket);
}
else
{
context.Response.StatusCode = 400; // Bad Request
context.Response.Close();
}
}
}
private async Task HandleWebSocketCommunication(WebSocket webSocket)
{
byte[] buffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
// Handle received WebSocket data
await HandleReceivedData(buffer, result.Count);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
In the code above, we create an HTTP listener and start listening for WebSocket requests on the specified URL. When a request is received, we check if it is a WebSocket request using the IsWebSocketRequest
property of the HttpListenerRequest
object. If it is, we accept the WebSocket connection using the AcceptWebSocketAsync
method and handle the WebSocket communication within the HandleWebSocketCommunication
method.
With these examples, you should now have a basic understanding of how to implement WebSocket communication in C. Remember to handle exceptions and error handling to ensure reliable WebSocket communication.
- Using the Same Authentication Token for Multiple Domains in a Mobile App
- Blazor Latest Interview Questions 2024
- .NET 9 Features: A Sneak Peek into the Future of .NET Core
- Boosting Performance with .NET 7 Runtime
- Is .NET Core 7 faster than NodeJS?
- Mastering Func and Action in C#
- Understanding Space Complexity in C#
- A Comprehensive Guide to Ace Your C# Interview
- DotNetCore Interview Cheatsheet
- Understanding Different Data Types in C#
- WebSocket Implementation in Java
- A Comprehensive Guide to WebSocket Implementation in Laravel
- Implementing WebSocket in NestJS – A Comprehensive Guide
- WebSocket Implementation in C#
- WebSocket Implementation with GoFiber
- Implementing WebSockets in DotNetCore
- WebSocket Implementation in Java
- Implementing WebSockets in Python
- WebSocket Implementation in C#
- Implementing WebSockets in Dart
- Implementing WebSockets in GoLang for Real-Time Communication
- Websocket API in C#: A Complete Guide
- WebSocket Implementation in Java
- Implementing WebSockets in Python
- WebSocket Implementation in C#
- Implementing WebSockets in Dart
- 10 Essential Tips for Developing a Flutter Application
- Use CupertinoDatePicker in Flutter for Year Picking in iOS Style
- WebSocket Implementation in C#