Modern applications require real-time data, for example, stock and cryptocurrency quotes, sports results, online chats, IoT devices, and notifications. Traditional HTTP requests are inefficient: the client is forced to constantly poll the server, wasting extra traffic and waiting for updates.

WebSocket solves this problem: it is a protocol for a persistent two-way connection between a client and a server. The server can independently send new data to the client, and the client can send commands and subscriptions to channels.
A simple analogy: you call a friend (handshake), the friend checks who is calling, and accepts the call (authentication), after which the line remains open, and you can exchange messages (data stream).
The advantages of WebSocket include a persistent connection without repeated requests, instant data delivery, resource savings, and two-way message exchange.
Connecting to a WebSocket using the Cryptocompare example
Cryptocompare provides streaming cryptocurrency data via WebSocket. For example, you can subscribe to the BTC/USD stream.
Below is a universal WebSocket client in PowerShell.
# WebSocket-Client.ps1 - Universal WebSocket client for
# receiving data
# Windows PowerShell >= 5.1
# Author: hypo69
# Creation date: 13/09/2025
#
#
# LICENSE (MIT)
#
<#
MIT License: https://opensource.org/licenses/MIT
#>
function Start-WebSocketClient {
<#
.SYNOPSIS
Universal WebSocket client with support for reconnection and
logging.
.DESCRIPTION
Connects to a WebSocket server, sends a subscription to a data stream
and outputs incoming messages to the console. Automatic
reconnection on disconnection.
.PARAMETER Url
WebSocket server URL (for example:
"wss://streamer.cryptocompare.com/v2?api_key=YOUR_API_KEY").
.PARAMETER SubscribeMessage
Subscription message in JSON format.
.PARAMETER ReconnectDelay
Delay in seconds before reconnection. Default is 5 sec.
.EXAMPLE
$Url = "wss://streamer.cryptocompare.com/v2?api_key=YOUR_API_KEY"
$SubscribeMessage = '{"action":"SubAdd","subs":
["5~CCCAGG~BTC~USD"]}'
Start-WebSocketClient -Url $Url -SubscribeMessage
$SubscribeMessage -ReconnectDelay 5
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, HelpMessage = "Specify the WebSocket server URL.")]
[string]$Url,
[Parameter(Mandatory, HelpMessage = "Subscription message in
JSON format.")]
[string]$SubscribeMessage,
[Parameter(Mandatory = $false, HelpMessage = "Reconnection delay (sec).")]
[int]$ReconnectDelay = 5
)
while ($true) {
try {
$ws = [System.Net.WebSockets.ClientWebSocket]::new()
$uri = [Uri]$Url
$ws.ConnectAsync($uri,
[Threading.CancellationToken]::None).Wait()
Write-Host "✓ Connection established with $Url" -
ForegroundColor Green
if ($SubscribeMessage) {
$bytes =
[System.Text.Encoding]::UTF8.GetBytes($SubscribeMessage)
$buffer = [System.ArraySegment[byte]]::new($bytes)
$ws.SendAsync($buffer,
[System.Net.WebSockets.WebSocketMessageType]::Text, $true,
[Threading.CancellationToken]::None).Wait()
Write-Host "► Subscription sent:
$SubscribeMessage" -ForegroundColor Cyan
}
$bufferSize = 1024
$buffer = New-Object byte[] $bufferSize
$segment = [System.ArraySegment[byte]]::new($buffer)
while ($ws.State -eq
[System.Net.WebSockets.WebSocketState]::Open) {
$receiveTask = $ws.ReceiveAsync($segment,
[Threading.CancellationToken]::None)
$receiveTask.Wait()
$message =
[System.Text.Encoding]::UTF8.GetString($buffer, 0,
$receiveTask.Result.Count)
Write-Host "◄ Received: $message"
}
}
catch {
Write-Host "▲ Error: $_" -ForegroundColor Red
}
Write-Host "І Reconnecting in $ReconnectDelay
seconds..." -ForegroundColor Yellow
Start-Sleep -Seconds $ReconnectDelay
}
}
# --- USAGE EXAMPLE ---
#
#======================================================================
# Uncomment and replace API_KEY with your Cryptocompare key
# $Url = "wss://streamer.cryptocompare.com/v2?api_key=YOUR_API_KEY"
# $SubscribeMessage = '{"action":"SubAdd","subs":
# ["5~CCCAGG~BTC~USD"]}'
# Start-WebSocketClient -Url $Url -SubscribeMessage
# $SubscribeMessage -ReconnectDelay 5
This approach has several important advantages. It is universal and suitable for any WebSocket stream, not limited to one service. Automatic reconnection is implemented: if the connection is lost, the client automatically restores it. The script can be easily adapted for different channels or data types by simply changing the subscription message. In addition, it can be extended to add logging to a file, filter incoming messages, process JSON, or integrate with a database.
Code explanation
- [System.Net.WebSockets.ClientWebSocket] — .NET class for connecting to a WebSocket.
- ConnectAsync — establishes a connection with the server.
- SendAsync — sends a subscription message to the server.
- ReceiveAsync — receives incoming messages.
- Auto-reconnection — implemented through an infinite
while ($true)loop andStart-Sleep. - Logging — outputting messages to the console with color indication.
Recommendations for working with WebSocket
- Always use the secure
wss://protocol. - Check API keys and authorization tokens.
- Filter only the necessary data.
- For large data streams, save messages to a file or database.
- Test reconnection and error handling in advance.