Websockets github

Websockets github DEFAULT

Logo

Welcome to websocket-sharp!

websocket-sharp supports:

Branches

Build

websocket-sharp is built as a single assembly, websocket-sharp.dll.

websocket-sharp is developed with MonoDevelop. So a simple way to build is to open websocket-sharp.sln and run build for websocket-sharp project with any of the build configurations (e.g. ) in MonoDevelop.

Install

Self Build

You should add your websocket-sharp.dll (e.g. ) to the library references of your project.

If you would like to use that dll in your Unity project, you should add it to any folder of your project (e.g. ) in the Unity Editor.

NuGet Gallery

websocket-sharp is available on the NuGet Gallery, as still a prerelease version.

You can add websocket-sharp to your project with the NuGet Package Manager, by using the following command in the Package Manager Console.

Unity Asset Store

websocket-sharp is available on the Unity Asset Store (Sorry, Not available now).

It works with Unity Free, but there are some limitations:

  • Security Sandbox of the Webplayer (The server is not available in Web Player)
  • WebGL Networking (Not available in WebGL)
  • Incompatible platform (Not available for such UWP)
  • Lack of dll for the System.IO.Compression (The compression extension is not available on Windows)
  • .NET Socket Support for iOS/Android (iOS/Android Pro is required if your Unity is earlier than Unity 5)
  • .NET API 2.0 compatibility level for iOS/Android

.NET API 2.0 compatibility level for iOS/Android may require to fix lack of some features for later than .NET Framework 2.0, such as the delegates (so i have added them in the asset package).

And it is priced at US$15. I believe your $15 makes this project more better, Thank you!

Usage

WebSocket Client

usingSystem; usingWebSocketSharp; namespaceExample { publicclassProgram { publicstaticvoidMain (string[] args) { using (varws=newWebSocket ("ws://dragonsnest.far/Laputa")) { ws.OnMessage+= (sender, e) =>Console.WriteLine ("Laputa says: "+e.Data); ws.Connect (); ws.Send ("BALUS"); Console.ReadKey (true); } } } }

Step 1

Required namespace.

The class exists in the namespace.

Step 2

Creating a new instance of the class with the WebSocket URL to connect.

varws=newWebSocket ("ws://example.com");

The class inherits the interface, so you can create it with the statement.

using (varws=newWebSocket ("ws://example.com")) { ... }

This will close the WebSocket connection with status code (going away) when the control leaves the block.

Step 3

Setting the events.

WebSocket.OnOpen Event

This event occurs when the WebSocket connection has been established.

ws.OnOpen+= (sender, e) => { ... };

is passed as , so you do not need to use it.

WebSocket.OnMessage Event

This event occurs when the receives a message.

ws.OnMessage+= (sender, e) => { ... };

A instance is passed as .

If you would like to get the message data, you should access or property.

property returns a , so it is mainly used to get the text message data.

property returns a , so it is mainly used to get the binary message data.

if (e.IsText) { // Do something with e.Data. ... return; } if (e.IsBinary) { // Do something with e.RawData. ... return; }

And if you would like to notify that a ping has been received, via this event, you should set the property to .

ws.EmitOnPing=true; ws.OnMessage+= (sender, e) => { if (e.IsPing) { // Do something to notify that a ping has been received. ... return; } };
WebSocket.OnError Event

This event occurs when the gets an error.

ws.OnError+= (sender, e) => { ... };

A instance is passed as .

If you would like to get the error message, you should access property.

property returns a that represents the error message.

And property returns a instance that represents the cause of the error if it is due to an exception.

WebSocket.OnClose Event

This event occurs when the WebSocket connection has been closed.

ws.OnClose+= (sender, e) => { ... };

A instance is passed as .

If you would like to get the reason for the close, you should access or property.

property returns a that represents the status code for the close.

property returns a that represents the reason for the close.

Step 4

Connecting to the WebSocket server.

If you would like to connect to the server asynchronously, you should use the method.

Step 5

Sending data to the WebSocket server.

The method is overloaded.

You can use the , , or method to send the data.

If you would like to send the data asynchronously, you should use the method.

ws.SendAsync (data, completed);

And also if you would like to do something when the send is complete, you should set to any delegate.

Step 6

Closing the WebSocket connection.

If you would like to close the connection explicitly, you should use the method.

The method is overloaded.

You can use the , , , , or method to close the connection.

If you would like to close the connection asynchronously, you should use the method.

WebSocket Server

usingSystem; usingWebSocketSharp; usingWebSocketSharp.Server; namespaceExample { publicclassLaputa : WebSocketBehavior { protectedoverridevoidOnMessage (MessageEventArgse) { varmsg=e.Data=="BALUS"?"I've been balused already...":"I'm not available now."; Send (msg); } } publicclassProgram { publicstaticvoidMain (string[] args) { varwssv=newWebSocketServer ("ws://dragonsnest.far"); wssv.AddWebSocketService<Laputa> ("/Laputa"); wssv.Start (); Console.ReadKey (true); wssv.Stop (); } } }

Step 1

Required namespace.

usingWebSocketSharp.Server;

The and classes exist in the namespace.

Step 2

Creating the class that inherits the class.

For example, if you would like to provide an echo service,

usingSystem; usingWebSocketSharp; usingWebSocketSharp.Server; publicclassEcho : WebSocketBehavior { protectedoverridevoidOnMessage (MessageEventArgse) { Send (e.Data); } }

And if you would like to provide a chat service,

usingSystem; usingWebSocketSharp; usingWebSocketSharp.Server; publicclassChat : WebSocketBehavior { privatestring_suffix; publicChat () : this (null) { } publicChat (stringsuffix) { _suffix=suffix??String.Empty; } protectedoverridevoidOnMessage (MessageEventArgse) { Sessions.Broadcast (e.Data+_suffix); } }

You can define the behavior of any WebSocket service by creating the class that inherits the class.

If you override the method, it will be called when the used in a session in the service receives a message.

And if you override the , , and methods, each of them will be called when each of the events (, , and ) occurs.

The method can send data to the client on a session in the service.

If you would like to get the sessions in the service, you should access the property (returns a ).

The method can send data to every client in the service.

Step 3

Creating a new instance of the class.

varwssv=newWebSocketServer (4649); wssv.AddWebSocketService<Echo> ("/Echo"); wssv.AddWebSocketService<Chat> ("/Chat"); wssv.AddWebSocketService<Chat> ("/ChatWithNyan", () =>newChat (" Nyan!"));

You can add any WebSocket service to your with the specified behavior and absolute path to the service, by using the or method.

The type of must inherit the class, and must have a public parameterless constructor.

The type of must inherit the class.

So you can use a class in the above Step 2 to add the service.

If you create a new instance of the class without a port number, it sets the port number to 80. So it is necessary to run with root permission.

Step 4

Starting the WebSocket server.

Step 5

Stopping the WebSocket server.

wssv.Stop (code, reason);

The method is overloaded.

You can use the , , or method to stop the server.

HTTP Server with the WebSocket

I have modified the , , and some other classes from Mono to create an HTTP server that allows to accept the WebSocket handshake requests.

So websocket-sharp provides the class.

You can add any WebSocket service to your with the specified behavior and path to the service, by using the or method.

varhttpsv=newHttpServer (4649); httpsv.AddWebSocketService<Echo> ("/Echo"); httpsv.AddWebSocketService<Chat> ("/Chat"); httpsv.AddWebSocketService<Chat> ("/ChatWithNyan", () =>newChat (" Nyan!"));

For more information, would you see Example3?

WebSocket Extensions

Per-message Compression

websocket-sharp supports the Per-message Compression extension (but does not support it with the context take over).

As a WebSocket client, if you would like to enable this extension, you should set the property to a compression method before calling the connect method.

ws.Compression=CompressionMethod.Deflate;

And then the client will send the following header in the handshake request to the server.

If the server supports this extension, it will return the same header which has the corresponding value.

So eventually this extension will be available when the client receives the header in the handshake response.

Ignoring the extensions

As a WebSocket server, if you would like to ignore the extensions requested from a client, you should set the property to in your constructor or initializing it, such as the following.

wssv.AddWebSocketService<Chat> ( "/Chat", () =>newChat () { // To ignore the extensions requested from a client.IgnoreExtensions=true } );

If it is set to , the service will not return the Sec-WebSocket-Extensions header in its handshake response.

I think this is useful when you get something error in connecting the server and exclude the extensions as a cause of the error.

Secure Connection

websocket-sharp supports the secure connection with SSL/TLS.

As a WebSocket client, you should create a new instance of the class with a wss scheme WebSocket URL.

varws=newWebSocket ("wss://example.com");

If you would like to set a custom validation for the server certificate, you should set the property to a callback for it.

ws.SslConfiguration.ServerCertificateValidationCallback= (sender, certificate, chain, sslPolicyErrors) => { // Do something to validate the server certificate. ... returntrue; // If the server certificate is valid. };

The default callback always returns .

As a WebSocket server, you should create a new instance of the or class with some settings for the secure connection, such as the following.

varwssv=newWebSocketServer (5963, true); wssv.SslConfiguration.ServerCertificate=newX509Certificate2 ("/path/to/cert.pfx", "password for cert.pfx");

HTTP Authentication

websocket-sharp supports the HTTP Authentication (Basic/Digest).

As a WebSocket client, you should set a pair of user name and password for the HTTP authentication, by using the method before calling the connect method.

ws.SetCredentials ("nobita", "password", preAuth);

If is , the client will send the credentials for the Basic authentication in the first handshake request to the server.

Otherwise, it will send the credentials for either the Basic or Digest (determined by the unauthorized response to the first handshake request) authentication in the second handshake request to the server.

As a WebSocket server, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before calling the start method, such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Basic; wssv.Realm="WebSocket Test"; wssv.UserCredentialsFinder=id=> { varname=id.Name; // Return user name, password, and roles.returnname=="nobita"?newNetworkCredential (name, "password", "gunfighter") :null; // If the user credentials are not found. };

If you would like to provide the Digest authentication, you should set such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Digest;

Query string, Origin header, and Cookies

As a WebSocket client, if you would like to send the query string in the handshake request, you should create a new instance of the class with a WebSocket URL that includes the Query string parameters.

varws=newWebSocket ("ws://example.com/?name=nobita");

If you would like to send the Origin header in the handshake request, you should set the property to an allowable value as the Origin header before calling the connect method.

ws.Origin="http://example.com";

And if you would like to send the cookies in the handshake request, you should set any cookie by using the method before calling the connect method.

ws.SetCookie (newCookie ("name", "nobita"));

As a WebSocket server, if you would like to get the query string included in a handshake request, you should access the property, such as the following.

publicclassChat : WebSocketBehavior { privatestring_name; ... protectedoverridevoidOnOpen () { _name=Context.QueryString["name"]; } ... }

If you would like to get the value of the Origin header included in a handshake request, you should access the property.

If you would like to get the cookies included in a handshake request, you should access the property.

And if you would like to validate the Origin header, cookies, or both, you should set each validation for it with your , for example, by using the method with initializing, such as the following.

wssv.AddWebSocketService<Chat> ( "/Chat", () =>newChat () { OriginValidator=val=> { // Check the value of the Origin header, and return true if valid.Uriorigin; return!val.IsNullOrEmpty () &&Uri.TryCreate (val, UriKind.Absolute, outorigin) &&origin.Host=="example.com"; }, CookiesValidator= (req, res) => { // Check the cookies in 'req', and set the cookies to send to// the client with 'res' if necessary.foreach (Cookiecookieinreq) { cookie.Expired=true; res.Add (cookie); } returntrue; // If valid. } } );

Connecting through the HTTP proxy server

websocket-sharp supports to connect through the HTTP proxy server.

If you would like to connect to a WebSocket server through the HTTP proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), by using the method before calling the connect method.

varws=newWebSocket ("ws://example.com"); ws.SetProxy ("http://localhost:3128", "nobita", "password");

I have tested this with Squid. It is necessary to disable the following option in squid.conf (e.g. ).

Logging

The class has the own logging function.

You can use it with the property (returns a ).

So if you would like to change the current logging level ( as the default), you should set the property to any of the enum values.

ws.Log.Level=LogLevel.Debug;

The above means a log with lower than cannot be outputted.

And if you would like to output a log, you should use any of the output methods. The following outputs a log with .

ws.Log.Debug ("This is a debug message.");

The and classes have the same logging function.

Examples

Examples using websocket-sharp.

Example

Example connects to the Echo server.

Example2

Example2 starts a WebSocket server.

Example3

Example3 starts an HTTP server that allows to accept the WebSocket handshake requests.

Would you access to http://localhost:4649 to do WebSocket Echo Test with your web browser while Example3 is running?

Supported WebSocket Specifications

websocket-sharp supports RFC 6455, and it is based on the following references:

Thanks for translating to japanese.

License

Sours: https://github.com/sta/websocket-sharp

Awesome WebSockets Awesome

A curated list of WebSockets related principles and technologies.

WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.

Contents

Tools per Language

Agnostic

  • Centrifugo - Scalable real-time messaging in language-agnostic way.
  • Websocketd - WebSockets the UNIX way - Full duplex messaging between web browsers and servers.
  • Nchan - Nchan is a scalable, flexible pub/sub server for the modern web, built as a module for the Nginx web server.
  • Apache-websocket - Apache WebSocket module.
  • MinnowServer - A super small and fast embedded HTTP(S) WebSocket server.
  • gwsocket - Fast, standalone, language-agnostic WebSocket server RFC6455 compliant.

C

  • Libwebsockets - It's a lightweight pure C library built to use minimal CPU and memory resources, and provide fast throughput in both directions as client or server.
  • Libwebsock - C library for easy WebSockets server.
  • Websocket - Websocket server written in C.
  • facil.io - A server/framework library for web applications, including Websockets and native pub/sub.
  • libuwsc - A Lightweight and fully asynchronous WebSocket client C library based on libubox for Embedded Linux.
  • mongoose - Mongoose Embedded Web Server Library - Mongoose is more than an embedded webserver. It is a multi-protocol embedded networking library with functions including TCP, HTTP client and server, WebSocket client and server, MQTT client and broker and much more.
  • WebSockets in C - A minimal implementation for embedded applications.

C++

  • Websocketpp - C++ Websocket client/server library.
  • QtWebSockets - The QtWebSockets module is an add-on for the Qt5 library.
  • Beast - HTTP and WebSocket built on Boost.Asio in C++11.
  • µWebSockets - Highly scalable WebSocket server & client library.
  • Simple-WebSocket-Server - A very simple, fast, multithreaded, platform independent WebSocket (WS) and WebSocket Secure (WSS) server and client library implemented using C++11, Boost.Asio and OpenSSL.
  • UEWebsocket - Unreal engine 4 websocket plugin for both c++ and blueprint developer.
  • IXWebSocket - Lightweight C++11 multi-threaded client library with TLS support.
  • LAppS - LAppS - Lua Application Server for micro-services with default communication over WebSockets.
  • libhv - A network library for developing TCP/UDP/SSL/HTTP/WebSocket client/server.

C#

  • ASP.NET SignalR - Incredibly simple real-time web for .NET.
  • WebSocketListener - Lightweight and highly scalable asynchronous WebSocket server for .NET/Mono.
  • websocket-rpc - WebSocket RPC library for .NET with auto JavaScript client code generation, supporting ASP.NET Core.
  • NetGain - A high performance websocket server library powering Stack Overflow.
  • websocket-manager - Real-Time library for ASP .NET Core.
  • WebSockets - Implementation of the WebSocket protocol, along with client and server integration components.
  • WebSockets support in ASP.NET Core - This article explains how to get started with WebSockets in ASP.NET Core.
  • unity-websocket-server - A simple, zero-dependency WebSocket server for Unity.

Erlang

  • Sockjs-erlang - WebSocket emulation - Erlang server.
  • Cowboy - Small, fast, modular HTTP server written in Erlang.
  • n2o - Erlang web server on websockets.
  • Kraken - Distributed Pubsub Server for Realtime Apps.

Go

  • Gorilla Websocket - WebSocket implementation for Go.
  • Websocket - Package Websocket implements a client and server for the WebSocket protocol as specified in RFC 6455.
  • Ws - Tiny WebSocket library for Go.
  • 1m-go-websockets - Handling 1M websockets connections in Go.
  • gotify/server - A simple server for sending and receiving messages in real-time per web socket.
  • nhooyr/websocket - A minimal and idiomatic WebSocket library for Go.
  • Centrifuge - Real-time messaging library for Go with scalability in mind.

Haskell

  • Websockets - A Haskell library for creating WebSocket-capable servers.
  • n2o - Haskell implementation of Erlang's n2o - web server on websockets.

Java VM

Clojure

  • Sente - Realtime web comms for Clojure/Script.
  • Chord - Library designed to bridge the gap between the triad of CLJ/CLJS, web-sockets and core.async.
  • Luminusweb - Luminus is a Clojure micro-framework based on a set of lightweight libraries.

Java

  • Project Tyrus - JSR 356: Java API for WebSocket - Reference Implementation.
  • Java-WebSocket - Barebones WebSocket client and server implementation written in 100% Java.
  • Atmosphere - Realtime Client Server Framework for the JVM, supporting WebSockets with Cross-Browser Fallbacks.
  • Webbit - Java event based WebSocket and HTTP server.

Kotlin

  • Scarlet - Tinder's Retrofit inspired WebSocket client for Kotlin, Java, and Android

Scala

  • Play - The high velocity web framework for Java and Scala.
  • Finagle-websocket - Finagle Websocket clients and servers.

Node.js

  • Socket.IO - Featuring the fastest and most reliable real-time engine.
  • Nodejs-websocket - Node.js module for websocket server and client.
  • WebSocket-Node - WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455).
  • Sockjs-node - WebSocket emulation - Node.js server.
  • Ws - : The fastest cross platform RFC-6455 WebSocket implementation for Node.js.
  • deepstream.io - Open realtime server a fast, secure and scalable realtime server for mobile, web & iot.
  • websocket-as-promised - Promise-based W3C WebSocket wrapper: allows to use promises when connecting, disconnecting and messaging with WebSocket server.
  • faye-websocket-node - Standards-compliant WebSocket client and server.
  • ws-wrapper - Lightweight WebSocket wrapper that provides a socket.io-like event-handler API along with Promise-based requests.
  • ws-server-wrapper - Companion library for ws-wrapper for the server-side.
  • uws - Tiny WebSockets (access to the C++ library, µWebSockets, via Node.js)
  • netflux - JavaScript client and server side transport API based on WebRTC & WebSocket
  • Sockette - WebSocket client that will automatically reconnect if the connection is lost.
  • rpc-websockets - JSON-RPC 2.0 implementation over WebSockets for Node.js and JavaScript/TypeScript.

Perl

PHP

  • Ratchet - Ratchet is a loosely coupled PHP library providing developers with tools to create real time, bi-directional applications between clients and servers over WebSockets.
  • Php-websocket - Simple PHP WebSocket implementation for PHP 5.3.
  • Phpws - PHP Web Socket server.
  • Sandstone - Microframework to build a real time Rest API.

Python

  • Django Channels - Extends Django with WebSocket, long-poll HTTP, task offloading and other async support.
  • Websockets - Websockets is a library for developing WebSocket servers and clients in Python 3.
  • Ws4py - WebSocket package for Python.
  • Autobahn.ws - Open-source real-time framework for Web, Mobile & Internet of Things.
  • Tornado - Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
  • WebSocket Benchmarker - CLI tool for benchmarking WebSocket Servers.

Ruby

  • AnyCable - Polyglot replacement for Ruby WebSocket servers with Action Cable protocol.
  • Em-websocket - EventMachine based WebSocket server.
  • Faye-websocket-ruby - Standards-compliant WebSocket client and server.
  • Iodine - WebSocket/HTTP server with integrated pub/sub and optional Redis support.
  • Websocket-driver-ruby - WebSocket protocol handler with pluggable I/O.
  • Websocket-ruby - Universal Ruby library to handle WebSocket protocol.
  • Scorched - Light-weight web framework for Ruby.
  • Firehose - Build realtime Ruby web applications. Created by the fine folks at Poll Everywhere.
  • Slanger - Open Pusher implementation compatible with Pusher libraries.
  • render_sync - Real-time Rails Partials.
  • websocket-rails - Plug and play websocket support for ruby on rails.

Rust

Protocols and APIs

GUI Testing Tools

  • Firecamp - Full-featured GUI WebSocket testing client which helps Dev team to test WebSocket events visually. Test APIs, save them in the project and share it with your team.
  • WebSocket King - A browser based WebSocket testing client that supports multiple simultanious connections, logs of incoming and outgoing messages, custom protocols and multiple projects.

Command-Line Interface (CLI) Tools

  • claws - Awesome WebSocket Client - an interactive command line client for testing websocket servers.
  • wscat - WebSocket cat.
  • wsta - A CLI development tool for WebSocket APIs.
  • ws - websocket command line tool.
  • wssh - wssh ("wish") is a command-line utility/shell for WebSocket inspired by netcat.
  • wsc - A tiny command line websocket client written in Go.
  • ws-cli - WebSocket Command Line Client written in Go.
  • ws-tool - A Develop Tool to Test WebSocket, Socket.IO, Stomp, Bayeux, HTTP, TCP, UDP, WebRTC, DNS API.
  • websocketd - Turn any program that uses STDIN/STDOUT into a WebSocket server. Like inetd, but for WebSockets.
  • websocat - Command-line client for WebSockets, like netcat (or curl) for ws:// with advanced socat-like functions.
  • iola - Socket client with Rest API (WebSocket, Socket.IO, TCP, Unix socket).

Real Life Stories

Security

  • WebSockets - An Introduction - The problems and some security implications of websockets - Cross-site WebSockets Scripting (XSWS).
  • Hacking with WebSockets - Talk on Blackhat USA 2012 Conference.
  • Testing for WebSockets Security Vulnerabilities - Interactive vulnerable WebSocket demos that provide hands-on learning of WebSocket security risks
  • Testing WebSockets - This article is part of the new OWASP Testing Guide v4.
  • Websockets Auth - Journey into WebSockets Authentication/Authorization.
  • WebSocket Security - The WebSocket protocol is a young technology, and brings with it some risks. Decades of experience have taught the web community some best practices around HTTP security, but the security best practices in the WebSocket world aren’t firmly established, and continue to evolve. Nevertheless, some themes have emerged and they are described in this article.
  • Cross-Site WebSocket Hijacking - Cross-Site WebSocket Hijacking (CSWSH) - Web Application Security Blog.

Theory

Articles & Papers

Talks

Tutorials

Books

Sites

License

CC0

Contributing

Please, read the Contribution Guidelines before submitting your suggestion.

Feel free to open an issue or create a pull request with your additions.

Thanks!

Acknowledgments

Table of contents generated with DocToc

Sours: https://github.com/facundofarias/awesome-websockets
  1. Vnet phone
  2. Dog watcher salary
  3. Electric diffuser walmart
  4. Tela gba
  5. 2010 c300 engine

ws: a Node.js WebSocket library

Version npmCICoverage Status

ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and server implementation.

Passes the quite extensive Autobahn test suite: server, client.

Note: This module does not work in the browser. The client in the docs is a reference to a back end with the role of a client in the WebSocket communication. Browser clients must use the native object. To make the same code work seamlessly on Node.js and the browser, you can use one of the many wrappers available on npm, like isomorphic-ws.

Table of Contents

Protocol support

  • HyBi drafts 07-12 (Use the option )
  • HyBi drafts 13-17 (Current default, alternatively option )

Installing

Opt-in for performance

There are 2 optional modules that can be installed along side with the ws module. These modules are binary addons which improve certain operations. Prebuilt binaries are available for the most popular platforms so you don't necessarily need to have a C++ compiler installed on your machine.

  • : Allows to efficiently perform operations such as masking and unmasking the data payload of the WebSocket frames.
  • : Allows to efficiently check if a message contains valid UTF-8.

API docs

See for Node.js-like documentation of ws classes and utility functions.

WebSocket compression

ws supports the permessage-deflate extension which enables the client and server to negotiate a compression algorithm and its parameters, and then selectively apply it to the data payloads of each WebSocket message.

The extension is disabled by default on the server and enabled by default on the client. It adds a significant overhead in terms of performance and memory consumption so we suggest to enable it only if it is really needed.

Note that Node.js has a variety of issues with high-performance compression, where increased concurrency, especially on Linux, can lead to catastrophic memory fragmentation and slow performance. If you intend to use permessage-deflate in production, it is worthwhile to set up a test representative of your workload and ensure Node.js/zlib will handle it with acceptable performance and memory usage.

Tuning of permessage-deflate can be done via the options defined below. You can also use and , which is passed directly into the creation of raw deflate/inflate streams.

See the docs for more options.

importWebSocket,{WebSocketServer}from'ws';constwss=newWebSocketServer({port: 8080,perMessageDeflate: {zlibDeflateOptions: {// See zlib defaults.chunkSize: 1024,memLevel: 7,level: 3},zlibInflateOptions: {chunkSize: 10*1024},// Other options settable:clientNoContextTakeover: true,// Defaults to negotiated value.serverNoContextTakeover: true,// Defaults to negotiated value.serverMaxWindowBits: 10,// Defaults to negotiated value.// Below options specified as default values.concurrencyLimit: 10,// Limits zlib concurrency for perf.threshold: 1024// Size (in bytes) below which messages// should not be compressed if context takeover is disabled.}});

The client will only use the extension if it is supported and enabled on the server. To always disable the extension on the client set the option to .

importWebSocketfrom'ws';constws=newWebSocket('ws://www.host.com/path',{perMessageDeflate: false});

Usage examples

Sending and receiving text data

importWebSocketfrom'ws';constws=newWebSocket('ws://www.host.com/path');ws.on('open',functionopen(){ws.send('something');});ws.on('message',functionincoming(message){console.log('received: %s',message);});

Sending binary data

importWebSocketfrom'ws';constws=newWebSocket('ws://www.host.com/path');ws.on('open',functionopen(){constarray=newFloat32Array(5);for(vari=0;i<array.length;++i){array[i]=i/2;}ws.send(array);});

Simple server

import{WebSocketServer}from'ws';constwss=newWebSocketServer({port: 8080});wss.on('connection',functionconnection(ws){ws.on('message',functionincoming(message){console.log('received: %s',message);});ws.send('something');});

External HTTP/S server

import{createServer}from'https';import{readFileSync}from'fs';import{WebSocketServer}from'ws';constserver=createServer({cert: readFileSync('/path/to/cert.pem'),key: readFileSync('/path/to/key.pem')});constwss=newWebSocketServer({ server });wss.on('connection',functionconnection(ws){ws.on('message',functionincoming(message){console.log('received: %s',message);});ws.send('something');});server.listen(8080);

Multiple servers sharing a single HTTP/S server

import{createServer}from'http';import{parse}from'url';import{WebSocketServer}from'ws';constserver=createServer();constwss1=newWebSocketServer({noServer: true});constwss2=newWebSocketServer({noServer: true});wss1.on('connection',functionconnection(ws){// ...});wss2.on('connection',functionconnection(ws){// ...});server.on('upgrade',functionupgrade(request,socket,head){const{ pathname }=parse(request.url);if(pathname==='/foo'){wss1.handleUpgrade(request,socket,head,functiondone(ws){wss1.emit('connection',ws,request);});}elseif(pathname==='/bar'){wss2.handleUpgrade(request,socket,head,functiondone(ws){wss2.emit('connection',ws,request);});}else{socket.destroy();}});server.listen(8080);

Client authentication

importWebSocketfrom'ws';import{createServer}from'http';constserver=createServer();constwss=newWebSocketServer({noServer: true});wss.on('connection',functionconnection(ws,request,client){ws.on('message',functionmessage(msg){console.log(`Received message ${msg} from user ${client}`);});});server.on('upgrade',functionupgrade(request,socket,head){// This function is not defined on purpose. Implement it with your own logic.authenticate(request,(err,client)=>{if(err||!client){socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');socket.destroy();return;}wss.handleUpgrade(request,socket,head,functiondone(ws){wss.emit('connection',ws,request,client);});});});server.listen(8080);

Also see the provided example using .

Server broadcast

A client WebSocket broadcasting to all connected WebSocket clients, including itself.

importWebSocket,{WebSocketServer}from'ws';constwss=newWebSocketServer({port: 8080});wss.on('connection',functionconnection(ws){ws.on('message',functionincoming(data,isBinary){wss.clients.forEach(functioneach(client){if(client.readyState===WebSocket.OPEN){client.send(data,{binary: isBinary});}});});});

A client WebSocket broadcasting to every other connected WebSocket clients, excluding itself.

importWebSocket,{WebSocketServer}from'ws';constwss=newWebSocketServer({port: 8080});wss.on('connection',functionconnection(ws){ws.on('message',functionincoming(data,isBinary){wss.clients.forEach(functioneach(client){if(client!==ws&&client.readyState===WebSocket.OPEN){client.send(data,{binary: isBinary});}});});});

echo.websocket.org demo

importWebSocketfrom'ws';constws=newWebSocket('wss://echo.websocket.org/',{origin: 'https://websocket.org'});ws.on('open',functionopen(){console.log('connected');ws.send(Date.now());});ws.on('close',functionclose(){console.log('disconnected');});ws.on('message',functionincoming(data){console.log(`Roundtrip time: ${Date.now()-data} ms`);setTimeout(functiontimeout(){ws.send(Date.now());},500);});

Use the Node.js streams API

importWebSocket,{createWebSocketStream}from'ws';constws=newWebSocket('wss://echo.websocket.org/',{origin: 'https://websocket.org'});constduplex=createWebSocketStream(ws,{encoding: 'utf8'});duplex.pipe(process.stdout);process.stdin.pipe(duplex);

Other examples

For a full example with a browser client communicating with a ws server, see the examples folder.

Otherwise, see the test cases.

FAQ

How to get the IP address of the client?

The remote IP address can be obtained from the raw socket.

import{WebSocketServer}from'ws';constwss=newWebSocketServer({port: 8080});wss.on('connection',functionconnection(ws,req){constip=req.socket.remoteAddress;});

When the server runs behind a proxy like NGINX, the de-facto standard is to use the header.

wss.on('connection',functionconnection(ws,req){constip=req.headers['x-forwarded-for'].split(',')[0].trim();});

How to detect and close broken connections?

Sometimes the link between the server and the client can be interrupted in a way that keeps both the server and the client unaware of the broken state of the connection (e.g. when pulling the cord).

In these cases ping messages can be used as a means to verify that the remote endpoint is still responsive.

import{WebSocketServer}from'ws';functionheartbeat(){this.isAlive=true;}constwss=newWebSocketServer({port: 8080});wss.on('connection',functionconnection(ws){ws.isAlive=true;ws.on('pong',heartbeat);});constinterval=setInterval(functionping(){wss.clients.forEach(functioneach(ws){if(ws.isAlive===false)returnws.terminate();ws.isAlive=false;ws.ping();});},30000);wss.on('close',functionclose(){clearInterval(interval);});

Pong messages are automatically sent in response to ping messages as required by the spec.

Sours: https://github.com/websockets/ws
Real-Time Streaming Stock Market Data with Python and Websockets

WebSocket Client & Server Implementation for Node

npm version

NPM Downloads

Codeship Status for theturtle32/WebSocket-Node

Overview

This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder.

You can read the full API documentation in the docs folder.

Changelog

Current Version: 1.0.34 - Release 2021-04-14

  • Updated browser shim to use the native property when available. See this MDN page for context. Resolves #415

View the full changelog

Browser Support

All current browsers are fully supported.

  • Firefox 7-9 (Old) (Protocol Version 8)
  • Firefox 10+ (Protocol Version 13)
  • Chrome 14,15 (Old) (Protocol Version 8)
  • Chrome 16+ (Protocol Version 13)
  • Internet Explorer 10+ (Protocol Version 13)
  • Safari 6+ (Protocol Version 13)

Benchmarks

There are some basic benchmarking sections in the Autobahn test suite. I've put up a benchmark page that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4.

(These benchmarks are quite a bit outdated at this point, so take them with a grain of salt. Anyone up for running new benchmarks? I'll link to your report.)

Autobahn Tests

The very complete Autobahn Test Suite is used by most WebSocket implementations to test spec compliance and interoperability.

Installation

In your project root:

Then in your code:

varWebSocketServer=require('websocket').server;varWebSocketClient=require('websocket').client;varWebSocketFrame=require('websocket').frame;varWebSocketRouter=require('websocket').router;varW3CWebSocket=require('websocket').w3cwebsocket;

Current Features:

  • Licensed under the Apache License, Version 2.0
  • Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake
  • Can handle/aggregate received fragmented messages
  • Can fragment outgoing messages
  • Router to mount multiple applications to various path and protocol combinations
  • TLS supported for outbound connections via WebSocketClient
  • TLS supported for server connections (use https.createServer instead of http.createServer)
    • Thanks to pors for confirming this!
  • Cookie setting and parsing
  • Tunable settings
    • Max Receivable Frame Size
    • Max Aggregate ReceivedMessage Size
    • Whether to fragment outgoing messages
    • Fragmentation chunk size for outgoing messages
    • Whether to automatically send ping frames for the purposes of keepalive
    • Keep-alive ping interval
    • Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly)
    • How long to wait after sending a close frame for acknowledgment before closing the socket.
  • W3C WebSocket API for applications running on both Node and browsers (via the class).

Known Issues/Missing Features:

  • No API for user-provided protocol extensions.

Server Example

Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary.

#!/usr/bin/env node varWebSocketServer=require('websocket').server;varhttp=require('http');varserver=http.createServer(function(request,response){console.log((newDate())+' Received request for '+request.url);response.writeHead(404);response.end();});server.listen(8080,function(){console.log((newDate())+' Server is listening on port 8080');});wsServer=newWebSocketServer({httpServer: server,// You should not use autoAcceptConnections for production// applications, as it defeats all standard cross-origin protection// facilities built into the protocol and the browser. You should// *always* verify the connection's origin and decide whether or not// to accept it.autoAcceptConnections: false});functionoriginIsAllowed(origin){// put logic here to detect whether the specified origin is allowed.returntrue;}wsServer.on('request',function(request){if(!originIsAllowed(request.origin)){// Make sure we only accept requests from an allowed originrequest.reject();console.log((newDate())+' Connection from origin '+request.origin+' rejected.');return;}varconnection=request.accept('echo-protocol',request.origin);console.log((newDate())+' Connection accepted.');connection.on('message',function(message){if(message.type==='utf8'){console.log('Received Message: '+message.utf8Data);connection.sendUTF(message.utf8Data);}elseif(message.type==='binary'){console.log('Received Binary Message of '+message.binaryData.length+' bytes');connection.sendBytes(message.binaryData);}});connection.on('close',function(reasonCode,description){console.log((newDate())+' Peer '+connection.remoteAddress+' disconnected.');});});

Client Example

This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number.

This code demonstrates a client in Node.js, not in the browser

#!/usr/bin/env node varWebSocketClient=require('websocket').client;varclient=newWebSocketClient();client.on('connectFailed',function(error){console.log('Connect Error: '+error.toString());});client.on('connect',function(connection){console.log('WebSocket Client Connected');connection.on('error',function(error){console.log("Connection Error: "+error.toString());});connection.on('close',function(){console.log('echo-protocol Connection Closed');});connection.on('message',function(message){if(message.type==='utf8'){console.log("Received: '"+message.utf8Data+"'");}});functionsendNumber(){if(connection.connected){varnumber=Math.round(Math.random()*0xFFFFFF);connection.sendUTF(number.toString());setTimeout(sendNumber,1000);}}sendNumber();});client.connect('ws://localhost:8080/','echo-protocol');

Client Example using the W3C WebSocket API

Same example as above but using the W3C WebSocket API.

varW3CWebSocket=require('websocket').w3cwebsocket;varclient=newW3CWebSocket('ws://localhost:8080/','echo-protocol');client.onerror=function(){console.log('Connection Error');};client.onopen=function(){console.log('WebSocket Client Connected');functionsendNumber(){if(client.readyState===client.OPEN){varnumber=Math.round(Math.random()*0xFFFFFF);client.send(number.toString());setTimeout(sendNumber,1000);}}sendNumber();};client.onclose=function(){console.log('echo-protocol Client Closed');};client.onmessage=function(e){if(typeofe.data==='string'){console.log("Received: '"+e.data+"'");}};

Request Router Example

For an example of using the request router, see in the folder.

Resources

A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. WebSockets: The Real-Time Web, Delivered

Sours: https://github.com/theturtle32/WebSocket-Node

Github websockets

Websocket API for Pricing Streaming and Real-Time Services

This API consists of a protocol specification. Also included is a set of example programs used to illustrate implementation of the protocol to make websocket connections to Refinitiv Real-Time Distribution Systems, and, to Refinitiv Real-Time -- Optimized (cloud offering) available via Refinitiv Data Platform (RDP). These examples are built using certain widely available Websocket frameworks and follow the protocol specification to demonstrate how to setup a websocket connection and use message constructs to receive Refinitiv Real-Time content. This API is governed by the same Apache 2 open source license as defined in the LICENSE.md file.

Example Code Disclaimer: ALL EXAMPLE CODE IS PROVIDED ON AN “AS IS” AND “AS AVAILABLE” BASIS FOR ILLUSTRATIVE PURPOSES ONLY. REFINITIV MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, AS TO THE OPERATION OF EXAMPLE CODE, OR THE INFORMATION, CONTENT OR MATERIALS USED IN CONNECTION WITH EXAMPLE CODE. YOU EXPRESSLY AGREE THAT YOUR USE OF EXAMPLE CODE IS AT YOUR SOLE RISK

Refinitiv Real-Time Distribution System Examples

These examples demonstrate the following usage:

  • Connecting, logging in, and requesting a single item
  • Requesting multiple items with a view in one message via a Batch Request
  • Posting content to an item
  • Logging in via Authentication
  • Monitoring connection health via Ping messages

The examples are found under the Applications/Examples folder. Examples are provided in the following languages:

  • C#
  • Java
  • Python
  • Perl
  • Node.js
  • Go
  • R
  • Ruby

More details for each example are included in a README.md file in its respective folder.

Refinitiv Data Platform Examples

These are examples written in Python, CSharp and Java that demonstrate consuming content from a Refinitiv Data Platform Real-Time Service.

The examples are found in the Applications/Examples/RDP folder with language specific sub-folders. More details are included in a README.md file in each example folder.

  • Authenticating via RDP, Connecting to a Refinitiv Real-Time service, and requesting a single item; examples handle session management or abiltiy to re-authenticate to renew authentication tokens
  • Discover which RDP endpoint to connect to by making a service discovery request to RDP and using this information to connect to the Refintiv Data Platform Real-Time Service to receive Real-Time content.

IMPORTANT NOTE: When specifying a 'region' as input to RDP Service Discovery applications, please consult [RTO documentation available on Refinitiv Developer Community] (https://developers.refinitiv.com/en/api-catalog/refinitiv-real-time-opnsrc/refinitiv-websocket-api/documentation) for a valid list of available regions. Default has been changed to "us-east-1" for region in sample applications starting with tag WSA-1.1.7.

In the event you would like to contribute to this repository, it is required that you read and sign the following:

Please email a signed and scanned copy to . If you require that a signed agreement has to be physically mailed to us, please email the request for a mailing address and we will get back to you on where you can send the signed documents.

Documentation for the WebSocket API and a Question & Answer forum are available at the WebSocket API Section of the Refinitiv Developer Community.

Issues raised via GitHub will be addressed in a best-effort manner. For broad questions regarding Websocket API, please refer to documentation and Q&A forum on Developer Community which is supported by an existing active community of API users.

Sours: https://github.com/Refinitiv/websocket-api
WebSockets in 100 Seconds \u0026 Beyond with Socket.io

WebSocket Server and Client for Arduino Build Status

a WebSocket Server and Client for Arduino based on RFC6455.

Supported features of RFC6455
  • text frame
  • binary frame
  • connection close
  • ping
  • pong
  • continuation frame
Limitations
  • max input length is limited to the ram size and the define
  • max output length has no limit (the hardware is the limit)
  • Client send big frames with mask 0x00000000 (on AVR all frames)
  • continuation frame reassembly need to be handled in the application code
Limitations for Async
  • Functions called from within the context of the websocket event might not honor and/or . See this issue for more info and a potential workaround.
  • wss / SSL is not possible.
Supported Hardware
  • ESP8266 Arduino for ESP8266
  • ESP32 Arduino for ESP32
  • ESP31B
  • Particle with STM32 ARM Cortex M3
  • ATmega328 with Ethernet Shield (ATmega branch)
  • ATmega328 with enc28j60 (ATmega branch)
  • ATmega2560 with Ethernet Shield (ATmega branch)
  • ATmega2560 with enc28j60 (ATmega branch)
Note:

version 2.0.0 and up is not compatible with AVR/ATmega, check ATmega branch.

version 2.3.0 has API changes for the ESP8266 BareSSL (may brakes existing code)

Arduino for AVR not supports std namespace of c++.

wss / SSL

supported for:

  • wss client on the ESP8266
  • wss / SSL is not natively supported in WebSocketsServer however it is possible to achieve secure websockets by running the device behind an SSL proxy. See Nginx for a sample Nginx server configuration file to enable this.

ESP Async TCP

This libary can run in Async TCP mode on the ESP.

The mode can be activated in the (see WEBSOCKETS_NETWORK_TYPE define).

ESPAsyncTCP libary is required.

High Level Client API

  • : Initiate connection sequence to the websocket host.
voidbegin(constchar *host, uint16_t port, constchar * url = "/", constchar * protocol = "arduino"); voidbegin(String host, uint16_t port, String url = "/", String protocol = "arduino");
  • : Callback to handle for websocket events
voidonEvent(WebSocketClientEvent cbEvent);
  • : Handler for websocket events
void (*WebSocketClientEvent)(WStype_t type, uint8_t * payload, size_t length)

Where is defined as:

typedefenum { WStype_ERROR, WStype_DISCONNECTED, WStype_CONNECTED, WStype_TEXT, WStype_BIN, WStype_FRAGMENT_TEXT_START, WStype_FRAGMENT_BIN_START, WStype_FRAGMENT, WStype_FRAGMENT_FIN, WStype_PING, WStype_PONG, } WStype_t;

Issues

Submit issues to: https://github.com/Links2004/arduinoWebSockets/issues

Join the chat at https://gitter.im/Links2004/arduinoWebSockets

License and credits

The library is licensed under LGPLv2.1

libb64 written by Chris Venter. It is distributed under Public Domain see LICENSE.

Sours: https://github.com/Links2004/arduinoWebSockets

You will also like:

websockets

licenceversionpyversionswheeltestsdocs

What is ?

is a library for building WebSocket servers and clients in Python with a focus on correctness and simplicity.

Built on top of , Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.

Documentation is available on Read the Docs.

Here's how a client sends and receives messages:

#!/usr/bin/env pythonimportasynciofromwebsocketsimportconnectasyncdefhello(uri): asyncwithconnect(uri) aswebsocket: awaitwebsocket.send("Hello world!") awaitwebsocket.recv() asyncio.run(hello("ws://localhost:8765"))

And here's an echo server:

#!/usr/bin/env pythonimportasynciofromwebsocketsimportserveasyncdefecho(websocket): asyncformessageinwebsocket: awaitwebsocket.send(message) asyncdefmain(): asyncwithserve(echo, "localhost", 8765): awaitasyncio.Future() # run foreverasyncio.run(main())

Does that look good?

Get started with the tutorial!


websockets for enterprise

Available as part of the Tidelift Subscription

The maintainers of websockets and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.


(If you contribute to and would like to become an official support provider, let me know.)

Why should I use ?

The development of is shaped by four principles:

  1. Simplicity: all you need to understand is and ; takes care of managing connections so you can focus on your application.
  2. Robustness: is built for production; for example it was the only library to handle backpressure correctly before the issue became widely known in the Python community.
  3. Quality: is heavily tested. Continuous integration fails under 100% branch coverage. Also it passes the industry-standard `Autobahn Testsuite`_.
  4. Performance: memory usage is configurable. An extension written in C accelerates expensive operations. It's pre-compiled for Linux, macOS and Windows and packaged in the wheel format for each system and Python version.

Documentation is a first class concern in the project. Head over to Read the Docs and see for yourself.

Why shouldn't I use ?

  • If you prefer callbacks over coroutines: was created to provide the best coroutine-based API to manage WebSocket connections in Python. Pick another library for a callback-based API.
  • If you're looking for a mixed HTTP / WebSocket library: aims at being an excellent implementation of RFC 6455: The WebSocket Protocol and RFC 7692: Compression Extensions for WebSocket. Its support for HTTP is minimal — just enough for a HTTP health check.

What else?

Bug reports, patches and suggestions are welcome!

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

For anything else, please open an issue or send a pull request.

Participants must uphold the Contributor Covenant code of conduct.

is released under the BSD license.

Sours: https://github.com/aaugustin/websockets


1060 1061 1062 1063 1064