In modern web applications, real-time communication is becoming increasingly important. Whether it is chat applications, online games, stock market push or collaborative editing tools, the server needs to be able to actively push data to the client. In the .NET ecosystem,WebSocketandSignalRThese are the two main solutions to implement this function.
This article will compare these two technologies, analyze their similarities and differences and usage scenarios, and provide simple sample code to help you get started quickly.
1. What is WebSocket?
WebSocket is a type provided by HTML5Full duplex communication protocol, allows the client to establish a persistent connection between the server and realizes two-way real-time communication. Compared with the traditional HTTP request-response mode, WebSocket is more efficient and suitable for applications that require frequent interactions.
WebSocket Features:
- Based on TCP protocol
- Supports two-way communication
- The connection is a long connection (stay open)
- Lightweight, high performance
- Need to manually manage connections and message processing
Use scenarios:
- Real-time data push (such as stock market)
- Online multiplayer game
- Multiple collaborative editing
- IoT device communication, etc.
2. What is SignalR?
SignalR is a Microsoft-developed.NET-based libraries, it simplifies the implementation of real-time communication. SignalR encapsulates a variety of transmission methods (including WebSocket, Server-Sent Events, long polling, etc.), and automatically selects the optimal method according to the browser and network environment.
SignalR Features:
- Abstract the underlying communication details
- Supports cross-platform (.NET Core/.NET 6+)
- Automatically downgrade browsers with poor compatibility
- Provides Hub model to easily organize business logic
- Integrate into Core
Use scenarios:
- Quickly build real-time features (no need to pay attention to the underlying communication details)
- Notification system in web applications
- Instant messaging (IM) applications
- Real-time dashboard, status monitoring
3. WebSocket vs SignalR comparison
characteristic | WebSocket | SignalR |
---|---|---|
Communication method | Full duplex | Full duplex (through package) |
Is it necessary to process the connection manually | ✅ Need | ❌ No need |
Whether multiplexing is supported | ❌ Not supported | ✅ Support (Hub) |
Whether automatic downgrade is supported | ❌ Not supported | ✅ Support (long polling, etc.) |
Development complexity | Higher | Lower |
performance | high | Slightly lower than WebSocket |
Suitable for scenes | High-performance, customized communications | Rapid development, universal real-time functions |
4. Sample code
Example 1: WebSocket Server + Client (.NET)
Server (Console Program)
using System; using ; using ; using ; using ; using ; class Program { static async Task Main(string[] args) { HttpListener listener = new HttpListener(); ("http://localhost:5000/"); (); ("WebSocket Server started on http://localhost:5000"); while (true) { HttpListenerContext context = await (); if () { WebSocketContext webSocketContext = await (null); _ = HandleWebSocketConnection(); } else { = 400; (); } } } private static async Task HandleWebSocketConnection(WebSocket socket) { byte[] buffer = new byte[1024 * 4]; while ( == ) { WebSocketReceiveResult result = await (new ArraySegment<byte>(buffer), ); string message = Encoding.(buffer, 0, ); ($"Received: {message}"); // Echo back the message byte[] response = Encoding.($"Echo: {message}"); await (new ArraySegment<byte>(response), , true, ); } } }
Client (JavaScript)
<!DOCTYPE html> <html> <head> <title>WebSocket Client</title> </head> <body> <input type="text" placeholder="Enter message" /> <button onclick="sendMessage()">Send</button> <div ></div> <script> const ws = new WebSocket('ws://localhost:5000'); = function (event) { ('output').innerText += + '\n'; }; function sendMessage() { const input = ('messageInput'); const message = ; (message); = ''; } </script> </body> </html>
Example 2: SignalR Server + Client (Core)
Server side (or)
var builder = (args); // Add services to the container. (); var app = (); <ChatHub>("/chatHub"); (); public class ChatHub : Hub { public async Task Send(string user, string message) { await ("ReceiveMessage", user, message); } }
Client (JavaScript)
<script src="/ajax/libs/microsoft-signalr/5.0.13/"></script> <input type="text" placeholder="User" /> <input type="text" placeholder="Message" /> <button onclick="sendMessage()">Send</button> <div ></div> <script> const connection = new () .withUrl("/chatHub") .build(); ("ReceiveMessage", function (user, message) { const msg = `${user}: ${message}`; ("chat").innerHTML += `<p>${msg}</p>`; }); ().catch(function (err) { return (()); }); function sendMessage() { const user = ("userInput").value; const message = ("messageInput").value; ("Send", user, message).catch(function (err) { return (()); }); ("messageInput").value = ""; } </script>
5. Summary
Scene | Recommended technology |
---|---|
High performance, low latency, custom protocol | WebSocket |
Rapid development, universal real-time functions | SignalR |
High browser compatibility requirements | SignalR |
Need to carefully control the communication process | WebSocket |
If you are developing a simple chat room or notification system,SignalR is the better choice; and if you need to build a high-performance, low-latency IoT communication system,WebSocket is more suitable。
6. Further reading
- Microsoft SignalR Documentation
- WebSocket W3C Standard Documentation
- Core WebSocket Support
This is the end of this article about WebSocket and SignalR: two options for real-time communication in C#. This is the end of this article. For more related contents of WebSocket and SignalR, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!