if __name__ == "__main__":
websocket.enableTrace(True)
ws = websocket.WebSocketApp("ws://localhost:8080",
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
ws.run_forever()
C# WebSocket client
C# 通过属于 System.NET.WebSockets 命名空间的 ClientWebSocket 类提供了 WebSocket 客户端。
下面的代码将连接到位于 wss://my-websocket-server.com 的 WebSocket 服务器。建立连接后,它将监听消息,在控制台上显示这些消息,并向服务器发送回复。
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketClientExample
class Program
private static async Task Main(string[] args)
Uri serverUri = new Uri("wss://my-websocket-server.com");
await ConnectWebSocketAsync(serverUri);
Console.ReadKey();
private static async Task ConnectWebSocketAsync(Uri serverUri)
using (ClientWebSocket webSocket = new ClientWebSocket())
await webSocket.ConnectAsync(serverUri, CancellationToken.None);
Console.WriteLine("WebSocket connection opened");
_ = Task.Run(async () =>
while (webSocket.State == WebSocketState.Open)
WebSocketReceiveResult result;
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
result = await webSocket.ReceiveAsync(buffer, CancellationToken.None);
string message = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);
Console.WriteLine("Received message: " + message);
while (!result.EndOfMessage);
// Send a message to the WebSocket server
string sendMessage = "Hello, WebSocket Server!";
ArraySegment<byte> sendBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(sendMessage));
await webSocket.SendAsync(sendBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
Console.WriteLine("Sent message: " + sendMessage);
JavaScript WebSocket client
JavaScript 是一种广泛采用的客户端 Web 开发语言。使用 JavaScript / HTML 创建 WebSocket client非常简单,因为该语言本身支持 WebSocket API。
const websocket = new WebSocket("wss://my-websocket-server.com");
websocket.onopen = function(event) {
console.log("Connected!");
websocket.send("Hello, WebSocket server!");
websocket.onmessage = function(event) {
console.log("Received message:", event.data);
websocket.onerror = function(event) {
console.log("Error:", event);
websocket.onclose = function(event) {
console.log("Connection closed");
Node.js WebSocket client
Node.js 是一种流行的运行时环境,用于在服务器端执行 JavaScript。要在 Node.js 中创建 WebSocket client,您可以使用“ws”库。
const WebSocket = require('ws');
const websocket = new WebSocket('wss://my-websocket-server.com');
websocket.on('open', function open() {
console.log('Connected!');
websocket.send('Hello, WebSocket server!');
websocket.on('message', function incoming(message) {
console.log('Received message:', message);
websocket.on('error', function error(err) {
console.log('Error:', err);
websocket.on('close', function close() {
console.log('Connection closed');
React WebSocket client
本示例在 React 中创建了一个简单的 WebSocket client 组件,当组件挂载时,它会连接到 WebSocket 服务器,监听消息并相应地更新状态。sendMessage 函数向 WebSocket 服务器发送消息。
import React, { useState, useEffect } from 'react';
const WebSocketClient = () => {
const [messages, setMessages] = useState([]);
const [ws, setWs] = useState(null);
useEffect(() => {
const websocket = new WebSocket('wss://my-websocket-server.com');
websocket.onopen = () => {
console.log('WebSocket connection opened');
websocket.onmessage = (event) => {
const newMessage = event.data;
setMessages((prevMessages) => [...prevMessages, newMessage]);
websocket.onclose = () => {
console.log('WebSocket connection closed');
websocket.onerror = (error) => {
console.error('WebSocket error:', error);
setWs(websocket);
return () => {
websocket.close();
}, []);
const sendMessage = (message) => {
if (ws) {
ws.send(message);
return (
<div id='myDiv'>
<h2>WebSocket Client</h2>
{messages.map((message, index) => (
<li key={index}>{message}</li>
<button onClick={() => sendMessage('Hello, WebSocket Server!')}>
Send Message
</button>
export default WebSocketClient;
Swift WebSocket client
下面的代码使用 URLSessionWebSocketTask API 来建立 WebSocket 连接、监听消息并将其打印到控制台。sendMessage
函数将向 WebSocket 服务器发送消息,并在 5 秒延迟后断开连接。
import Foundation
class WebSocketClient {
private let url: URL
private var webSocketTask: URLSessionWebSocketTask?
init(url: URL) {
self.url = url
func connect() {
let session = URLSession(configuration: .default)
webSocketTask = session.webSocketTask(with: url)
webSocketTask?.resume()
receiveMessage()
func disconnect() {
webSocketTask?.cancel(with: .goingAway, reason: nil)
private func receiveMessage() {
webSocketTask?.receive { [weak self] result in
switch result {
case .success(let message):
switch message {
case .string(let text):
print("Received message: \(text)")
case .data(let data):
print("Received data: \(data)")
@unknown default:
print("Unknown message")
self?.receiveMessage()
case .failure(let error):
print("Error receiving message: \(error)")
func sendMessage(_ message: String) {
webSocketTask?.send(.string(message)) { error in
if let error = error {
print("Error sending message: \(error)")
} else {
print("Sent message: \(message)")
let serverUrl = URL(string: "wss://my-websocket-server.com")!
let webSocketClient = WebSocketClient(url: serverUrl)
webSocketClient.connect()
// Send a message to the WebSocket server
webSocketClient.sendMessage("Hello, WebSocket Server!")
// Disconnect after a delay
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
webSocketClient.disconnect()
Golang WebSocket client
这个用 Go 编写的简单 WebSocket client 示例使用了流行的 github.com/gorilla/websocket
软件包。它建立一个 WebSocket 连接,监听消息并将消息打印到控制台。客户端每秒向 WebSocket 服务器发送一条消息,收到中断信号(如 Ctrl+C)后关闭连接。
package main
import (
"fmt"
"log"
"net/url"
"os/signal"
"time"
"github.com/gorilla/websocket"
var interrupt chan os.Signal
func main() {
interrupt = make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "ws", Host: "my-websocket-server.com", Path: "/"}
fmt.Printf("Connecting to %s\n", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("Error during reading message:", err)
return
fmt.Printf("Received: %s\n", message)
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-done:
return
case t := <-ticker.C:
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
log.Println("Error during writing message:", err)
return
fmt.Printf("Sent: %s\n", t.String())
case <-interrupt:
log.Println("Interrupt received, closing connection")
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("Error during closing connection:", err)
return
select {
case <-done:
case <-time.After(time.Second):
return
使用 WebSocket clients 构建实时应用程序
通过利用 WebSocket clients,开发人员可以创建功能强大、反应灵敏的应用程序,以满足现代用户的需求。实时应用的范围包括聊天应用、在线游戏、实时数据流和协作平台。
以下是使用 WebSocket clients 构建实时应用程序时应遵循的一些步骤:
处理 WebSocket 事件: 如前所述,处理 WebSocket 事件(如 onopen、onmessage、onerror 和 onclose)对于管理 WebSocket 连接的生命周期至关重要。在应用程序中实施所需的事件处理程序,以交换信息和处理错误。
本文来自作者投稿,版权归原作者所有。如需转载,请注明出处:https://www.nxrte.com/jishu/41290.html
赞 (0)
MLow:Meta 的低比特率音频编解码器
用于学习图像压缩的多级空间上下文模型 | ICASSP 2023
前端直播功能开发(React/Next/Vue/Angular等框架),请务必收下这篇教程
如何使用 FFmpeg 调整音量(包括音量、DRC、标准化)
Visionular 与 Ant Media 宣布战略合作,革新直播和视频压缩
WebRTC SDP 简介
Gcore 推出 AI 驱动的边缘 Web 应用程序和 API 保护