Lawrence  Lesch

Lawrence Lesch

1664338680

Spacebro-client: Easily Share Event Between Application

Spacebro client

🌟 Connect easily to a spacebro server.

🌍 Installation

yarn add spacebro-client
# or
npm i -S spacebro-client

👋 Usage

First, you need to start a spacebro server.

$ npm i -g spacebro # or yarn global add spacebro
$ spacebro

Then, write the following client code:

const { SpacebroClient } = require('spacebro-client')

const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 36000,
  channelName: 'bar',
  client: {
    name: 'foo',
    description: "a foo tool",
    in: {
      inFoo: {
        eventName: "inFoo",
        description: "Input foo",
        type: "all"
      }
    },
    out: {
      outBar: {
        eventName: "outBar",
        description: "Output bar",
        type: "all"
      }
    }
  },
  connection: "bar/outBar => bar/inFoo"
})

client.on('inFoo', (data) => console.log('inFoo', data))
client.emit('outBar', { do: stuff})

The connection string was sent to the spacebro server, that will then connects every event named outBar from client bar to a new event named inFoo sent to client bar

🚀 API

class SpacebroClient([options], [connect])

Look for a server, and return a handle to the connection.

// For more details about possible options, see below.
const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 8888,
  client: {name: 'foo'},
  channelName: 'bar'
})

options:

namedefaultrequireddescription
host-requiredThe spacebro server's address. Ignored if connect is false.
port-requiredThe spacebro server's address. Ignored if connect is false.
client.namenullrecommendedYour client's name. Can be useful to perform targeted events and for monitoring.
channelNamenullrecommendedThe channel your app will communicate in. This is especially usefull if you have multiple apps using the same server.
verbosetrueoptionalShould spacebro-client display logs (connection / emission / reception)?
sendBacktrueoptionalShould this client receive the events it sent?

connect

If the connect parameter is false, then the options are saved and a disconnected handle is returned; you have to call its connect method later before you can emit or receive events.

Default value: true

const client = new SpacebroClient({
  client: {name: 'myClient'},
  channelName: 'someChannel'
}, false)

// ...

client.connect('127.0.0.1', 8888)

create([options])

Look for a server, and creates a handle to the connection. Takes the same options as new SpacebroClient. Returns a Promise like client.connect.

setDefaultSettings(options, [verbose])

Overwrite the default options of new SpacebroClient with the given options.

If standard-settings is installed in your module, spacebro-client will call this function with the contents of services.spacebro from your settings file.

client.connect(address, port)

Look for a server, and connect client to this server. Returns a Promise that resolves to client when the connection is established, or throws an error if the connection fails.

client.emit(eventName[, data])

Broadcast a specific event to all the clients in the channel. data must be a JSON object.

client.sendTo(eventName, target[, data])

Send an event to a specific target in the channel. data must be a JSON object.

client.on(eventName, handler)

Listen to a specific event.

client.once(eventName, handler)

Listen to a specific event only once.

client.off(eventName)

Remove a specific event listener.

client.disconnect()

Close the connection.

Socket.io callbacks (acknowledgments)

Spacebro now works with acknowlegdments too !

const { SpacebroClient } = require('spacebro-client')

const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 36000,
  channelName: 'bar',
  client: {
    name: 'foo',
    description: "a foo tool",
    in: {
      inFoo: {
        eventName: "inFoo",
        description: "Input foo",
        type: "all"
      }
    },
    out: {
      outBar: {
        eventName: "outBar",
        description: "Output bar",
        type: "all"
      }
    }
  },
  connection: "bar/outBar => bar/inFoo"
})

client.on('inFoo', (data, fn) => {
  console.log('inFoo', data)
  fn('thank you')
})

client.emit('outBar', { do: stuff}, function (data) {
  console.log('Received from callback: ' + data)
})

🖥 Browser

You can use spacebro-client in the browser. You will need the following dependencies:

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.0/socket.io.js"></script>
<script src="https://wzrd.in/standalone/socketio-wildcard@latest"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-signals/1.0.0/js-signals.min.js"></script>

After adding these dependencies, you can include the spacebro-client lib like any script:

<script src="./dist/spacebro-client.js"></script>

Then use the window.spacebroClient object.

⚛ Electron

Spacebro-client also works in Electron. You just require('spacebro-client') in your electron main process and use ipc or web-contents to forward events to the renderer process.

From the example/electron/ folder of this repository:

// In the main process.
const { app, BrowserWindow } = require('electron')
const { SpacebroClient } = require('../../dist/spacebro-client')

let win = null

const client = new SpacebroClient({
  host: '127.0.0.1',
  port: 8888,
  client: {name: 'foo'},
  channelName: 'bar'
})

app.on('ready', () => {
  win = new BrowserWindow({ width: 800, height: 600 })
  win.loadURL(`file://${__dirname}/index.html`)

  for (const eventName of ['hello', 'world']) {
    client.on(eventName, (data) => {
      win.webContents.send(eventName, data)
    })
  }

  win.webContents.on('did-finish-load', () => {
    setTimeout(() => { client.emit('hello', { hello: 'world' }) }, 3000)
    setTimeout(() => { client.emit('world', { world: 'hello' }) }, 5000)
  })
})
<!-- index.html -->
<html>
<body>
  <script>
    require('electron').ipcRenderer.on('hello', (event, message) => {
      console.log(message)
    })
    require('electron').ipcRenderer.on('world', (event, message) => {
      console.log(message)
    })
  </script>
</body>
</html>

Examples

You can find many real life examples in the example/ folder of this repository.

🕳 Troubleshooting

newClient event 👋

The Spacebro server automatically broadcasts a newClient event when a client connects. Thus, you should avoid using that event name. See the example/simple-node script for more details.

Using native modules in Electron 🌀

If you want to use spacebro-client in an Electron app, you'll have to use electron-rebuild in order to rebuild MDNS according to the version of Node.js embedded with Electron.

Use the following commands:

$ npm i --save-dev electron-rebuild # or yarn
$ ./node_modules/.bin/electron-rebuild # call the executable every time you add a new native module

You can also add "rebuild": "./node_modules/.bin/electron-rebuild" to your package.json and run npm run rebuild for convenience.

source

yarn and node-gyp issue (i.e not compiling) 🤖

You need to use at least yarn version 0.17.8. You might have similar problems with outdated versions of npm, simply try to update it.

source

https

If the spacebro server is on https, use following settings:

  'service': {
    'spacebro': {
      'host': 'https://example.com'
      'port': 0
    }
  }

subdir on server

If the server url is something like https://example.com/subdir. You can use this url as host. Spacebro will process subdir as a path, contrary to socket.io that would process subdir as a namespace.

That means the requested urls will look like https://example.com/subdir/?EIO=3&transport=polling&sid=<id>

ping pong 🏓

Do not try to test with 'ping' and 'pong' events, those are reserved.

- `ping`. Fired when a ping packet is written out to the server.
- `pong`. Fired when a pong is received from the server.

source

❤️ Contribute

Please follow Standard JS conventions.

The package has lint testing and unit testing baked-in. Please use npm run test to run both sets of tests before making a pull request. Use npm run build to transpile the project.

The project's release versions are named after stars in Andromeda . The current version is named Sirrah.

Enjoy !

Download Details:

Author: Spacebro
Source Code: https://github.com/spacebro/spacebro-client 
License: MIT license

#javascript #client #websocket #socket #realtime 

Spacebro-client: Easily Share Event Between Application
Lawrence  Lesch

Lawrence Lesch

1664334720

Spacebro Makes Communication Between Apps Effortless

🚀 Spacebro 💫

In reference to Spacebrew by Rockwell Lab (http://www.rockwellgroup.com/search/LAB)

Prerequisites

Spacebro uses:

Usage

As a CLI tool

Install it globally

$ npm i -g spacebro
# or
$ yarn global add spacebro

And just run the bin :

$ spacebro

You can configure it via CLI args:

$ spacebro --server.port 8888
# to view all possible arguments
$ spacebro --help

NOTE: Spacebro uses standard-settings, see the doc there to change settings via argv, env or file

As a module

$ npm i --save spacebro
# or
$ yarn add spacebro

And then connection with a spacebro-client as is. The spacebro client allows to connect your node application to spacebro server, just by requiring it.

See spacebro-client to learn more.

For openFramework you can also use ofxSpaceBro.

For python you can also use pySpacebroClient.

Options

flagwhat it does
-h, --helpoutput usage information
-V, --versionoutput the version number
-P, --server.port <n>give a port to spacebro
-M, --muteoption to hide informations
--semiverbosedo not show events datas in logs
-H, --hidedashboardAllow to hide dashboard

API

Once connected, you can interact with spacebro, to know which other client is connected, what are the connections between them, add your own connections, ...

A connection is a link between an output of a client and an input of an other client. It is explained in details below.

register

Mandatory event for a client to send to spacebro, this is implemented inside spacebro-client so you should not have to use this, unless you are writing a client plugin in an other language.

The data sent with the register event should include the keys below:

{
  channelName: 'media-stream', // the socket.io channel to connect to
  client: {
    name: 'myclientname',
    description: 'Describe here what your client does',
    in: {// input events your client will react to
      inMedia: {
        eventName: "inMedia",
        description: "Describe the input event here",
        type: "all" // use all by default, or mention a type of data
expected
      },
      otherInput: {
        ...
      }
    },
    out: { // output events your client will send
      outMedia: {
        eventName: "outMedia",
        description: "Describe the input event here",
        type: "all" // use all by default, or mention a type of data
      }
    }
  }
}

addConnections

Add a connection between an output of a client and the input of an other client.

The data can be a connection or an array of connections with a connection respecting this schema

{
  src: {
    clientName: 'myclient',
    eventName: 'outMedia'
  },
  tgt: {
    clientName: 'myotherclient',
    eventName: 'inMedia'
  }
}

or a string or array of strings with this syntax:

myclient/outMedia => myotheclient/inMedia

When myclient emits a outMedia event, it will be forwarded to myotherclient with the event name inMedia

A connection event is emitted to all clients with the updated

removeConnections

Removes all connections listed in the data of this event: an array or single connection, in the schema seen above.
A connection event is emitted to all clients with the updated connections list

replaceConnections

Removes all connections on the current channel, and add the connections listed in the data of this event.
A connection event is emitted to all clients with the updated connections list

getConnections

Ask for a connection event, which is emitted to all clients with the current connection list on the current channel.

getClients

Ask for a clients event, which is emitted to all clients with the current client list on the current channel.

saveGraph

Save the current state: list of clients and list of connections, into the settings file mentioned when running spacebro

For example, run

spacebro --settings /path/to/my-settings-file.json

Connect some clients, add some connections, send a saveGraph event, and the state of the graph will be saved in this settings file.

Events

newClient

spacebro broadcasts a newClient event when a new connection is created, with the client name as client.name property value. Typically, you'd do on the client side:

spacebroClient.on('newClient', (data) => {
  console.log(`${data.client.name} has joined.`)
})

clients

spacebro broadcasts a clients event after a client registered or after receiving a getClients event.

data is an array of clients.

connections

spacebro broadcasts a connections event after a new connection is added or after receiving a getConnections event.

data is an array of connections in the schema descibed below:

{
  src: {
    clientName: 'myclient',
    eventName: 'outMedia'
  },
  tgt: {
    clientName: 'myiotherclient',
    eventName: 'inMedia'
  }
}

Troubleshooting

ping pong

Do not try to test with 'ping' and 'pong' events, those are reserved.

- `ping`. Fired when a ping packet is written out to the server.
- `pong`. Fired when a pong is received from the server.

source

Test

npm run test

Contribute

You can develop on spacebro, by running:

yarn dev

you can build with yarn build

We use galaxies names for our release name, listed here here. We are currently at Black Eye.

You can check the examples/ folder, as well as the spacebro-client examples for real life examples.

Please follow standard style conventions.

Download Details:

Author: Spacebro
Source Code: https://github.com/spacebro/spacebro 

#javascript #websocket #socket #realtime 

Spacebro Makes Communication Between Apps Effortless

A Plugin for using Websocket in Flutter

flutter_socket

flutter连接websocket插件,基于安卓Java-WebSocket:1.4.0插件

开始使用

使用工具类

final util = FlutterWebSocketUtil();

1.连接

必填参数:url 服务端的socket连接地址

可选参数1:onClose 连接被断开回调

可选参数2:onMessage 收到消息回调

可选参数3:onOpen 连接成功回调,调用一次

可选参数4:onError 连接失败回调

连接后会启动一个后台服务(service),通知栏可能会显示一个正在运行的通知



  
                  util.connect(
                    url: _url,
                    onClose: (SocketConnectCloseModel detail) {
                      print('是否远程地址:${detail.remote}');
                      print('连接被断开code:${detail.code}');
                      print('连接被断开:${detail.message}');
                    },
                    onMessage: (String message) {
                      print('收到消息:$message');
                    },
                    onOpen: (String url) {
                      print('连接成功,地址是:$url');
                    },
                    onError: (String message) {
                      print('连接失败:$message');
                    });

  

2.断开连接

util.close();

3.开启心跳检测

30秒检测一次

util.openHeart();

4.检测是否连接

 FlutterSocket.isOpen();

5.发送消息

util.send("hello world");

工具类

import 'package:erp_system/config/ip.dart';
import 'package:erp_system/utils/extend_util.dart';
import 'package:erp_system/utils/user_util.dart';
import 'package:flutter_socket/connect_close_model.dart';
import 'package:flutter_socket/flutter_socket_util.dart';

class WebSocketUtilsV3 {
  WebSocketUtilsV3._();

  static final WebSocketUtilsV3 _instance = WebSocketUtilsV3._();

  factory WebSocketUtilsV3() => _instance;

  final util = FlutterWebSocketUtil();

  // 初始化socket连接
  Future<void> init() async {
    final user = await getCatchUser();
    if (user != null) {
      final _connectUrl = 'ws://$kHost:$kPort/websocket';
      util.connect(url: _connectUrl, onOpen: onOpen, onClose: onClose, onMessage: onMessage, onError: onError);
    }
  }

  // 连接打开
  void onOpen(String url) {
    log('连接成功啦;$url');
    util.openHeart();
  }

  // 连接关闭
  void onClose(SocketConnectCloseModel detail) {
    log('连接被断开啦:${detail.code}');
  }

  // 收到消息
  void onMessage(String message) {
    log('收到消息啦:$message');
  }

  // 连接失败
  void onError(String message) {
    log('连接错误啦:$message');
  }
}

运行示例

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_socket

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  flutter_socket: ^1.0.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:flutter_socket/flutter_socket.dart'; 

example/lib/main.dart

import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_socket/connect_close_model.dart';
import 'package:flutter_socket/flutter_socket.dart';
import 'package:flutter_socket/flutter_socket_util.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final String _url = 'ws://192.168.199.63:8088/websocket/3/phone';

  // String _url = 'ws://192.168.199.63:8088/phone';

  final util = FlutterWebSocketUtil();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Container(
          height: MediaQueryData.fromWindow(window).size.height,
          width: MediaQueryData.fromWindow(window).size.width,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              renderBtn("初始化连接", () {
                util.connect(
                    url: _url,
                    onClose: (SocketConnectCloseModel detail) {
                      print('是否远程地址:${detail.remote}');
                      print('连接被断开code:${detail.code}');
                      print('连接被断开:${detail.message}');
                    },
                    onMessage: (String message) {
                      print('收到消息:$message');
                    },
                    onOpen: (String url) {
                      print('连接成功,地址是:$url');
                    },
                    onError: (String message) {
                      print('连接失败:$message');
                    });
              }),
              renderBtn("断开连接", util.close),
              renderBtn("开启心跳", util.openHeart),
              renderBtn("检测是否已经连接", FlutterSocket.isOpen),
              renderBtn("是否打开了GPS设置", ()async{
              final isOpen = await  FlutterSocket.gpsIsOpen();
              print('gps是否打开:$isOpen');
              }),
              renderBtn("打开gps设置页面", FlutterSocket.openGPSSystemPage)
            ],
          ),
        ),
      ),
    );
  }

  // 渲染按钮
  Widget renderBtn(String text, Function onTap) {
    return MaterialButton(
        color: Colors.blue,
        onPressed: onTap,
        child: Text(
          '$text',
          style: TextStyle(color: Colors.white),
        ));
  }
} 

Download Details:

Author: mdddj

Source Code: https://github.com/mdddj/flutter_websocket

#flutter #websocket 

A Plugin for using Websocket in Flutter
Cody  Osinski

Cody Osinski

1663891740

Libraries for Working with WebSocket in Popular Python

In this Python article, let's learn about WebSocket: Libraries for Working with WebSocket in Popular Python

Table of contents:

  • autobahn-python - WebSocket & WAMP for Python on Twisted and asyncio.
  • channels - Developer-friendly asynchrony for Django.
  • websockets - A library for building WebSocket servers and clients with a focus on correctness and simplicity.

What is Python?

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed

websockets?

websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio , Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.


Libraries for working with WebSocket

  1. autobahn-python

WebSocket and WAMP in Python for Twisted and asyncio

Autobahn|Python is a subproject of Autobahn and provides open-source implementations of

for Python 3.7+ and running on Twisted and asyncio.

You can use Autobahn|Python to create clients and servers in Python speaking just plain WebSocket or WAMP.

WebSocket allows bidirectional real-time messaging on the Web and beyond, while WAMP adds real-time application communication on top of WebSocket.

WAMP provides asynchronous Remote Procedure Calls and Publish & Subscribe for applications in one protocol running over WebSocket. WAMP is a routed protocol, so you need a WAMP Router to connect your Autobahn|Python based clients. We provide Crossbar.io, but there are other options as well.

Note

Autobahn|Python up to version v19.11.2 supported Python 2 and 3.4+, and up to version v20.7.1 supported Python 3.5+, and up to version v21.2.1 supported Python 3.6+.

View on GitHub


2.  Channels

Channels augments Django to bring WebSocket, long-poll HTTP, task offloading and other async support to your code, using familiar Django design patterns and a flexible underlying framework that lets you not only customize behaviours but also write support for your own protocols and needs.

Documentation, installation and getting started instructions are at https://channels.readthedocs.io

Channels is an official Django Project and as such has a deprecation policy. Details about what's deprecated or pending deprecation for each release is in the release notes.

Support can be obtained through several locations - see our support docs for more.

You can install channels from PyPI as the channels package. See our installation and tutorial docs for more.

Dependencies

All Channels projects currently support Python 3.7 and up. channels is compatible with Django 2.2, 3.2, 4.0 and 4.1.

Contributing

To learn more about contributing, please read our contributing docs.

View on GitHub


3.  websockets

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

Built on top of asyncio, 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 python

import asyncio
from websockets import connect

async def hello(uri):
    async with connect(uri) as websocket:
        await websocket.send("Hello world!")
        await websocket.recv()

asyncio.run(hello("ws://localhost:8765"))

And here's an echo server:

#!/usr/bin/env python

import asyncio
from websockets import serve

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message)

async def main():
    async with serve(echo, "localhost", 8765):
        await asyncio.Future()  # run forever

asyncio.run(main())

View on GitHub


Frequently asked questions about WebSocket

  • What is WebSocket used for?

The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.

  • What is WebSocket and how it works?

WebSocket is an upgraded, quick, and seamless protocol to use when one needs to establish constant client-server communication. Even if the data is continuously transmitted, WebSocket ensure the connection is intact and data is highly secured in the process.

  • How do I run a WebSocket in Python?

WebSocket Client with Python

Create a new File “client.py” and import the packages as we did in our server code. Now let's create a Python asynchronous function (also called coroutine). async def test(): We will use the connect function from the WebSockets module to build a WebSocket client connection.

  • What is WebSocket VS API?

APIs are the best option for applications where you just need basic CRUD operations and synchronous responses. Also, APIs can be used with both web and mobile applications and service integrations with ease. But, if your web application requires real-time communication with the backend, you should choose WebSockets.

  • Is WebSocket better than HTTP?

All the frequently updated applications used WebSocket because it is faster than HTTP Connection. When we do not want to retain a connection for a particular amount of time or reuse the connection for transmitting data; An HTTP connection is slower than WebSockets.


Related videos:

How to Create a WebSocket Client in Python - Fun with WebSockets


Related posts:

#python #websocket 

Libraries for Working with WebSocket in Popular Python
Ssekidde  Nat

Ssekidde Nat

1662725541

7 Most Popular Websocket Utilities Libraries In Python

In this Python article, let's learn about Websocket Utilities: 7 Most Popular Websocket Utilities Libraries In Python

Table of contents:

  • daphne: Django Channels HTTP/WebSocket server
  • websockify: Websockify is a WebSocket to TCP proxy/bridge. This allows a browser to connect to any application/server/service.
  • Flask-Sockets: Elegant WebSockets for your Flask apps.
  • gevent-socketio: Official repository for gevent-socketio
  • SockJS-tornado: WebSocket emulation - Python server
  • TornadIO2: Python socket.io server implementation on top of Tornado framework

 

5 Most Popular Websocket Utilities Libraries In Python

1.daphne

Daphne is a HTTP, HTTP2 and WebSocket protocol server for ASGI and ASGI-HTTP, developed to power Django Channels.

It supports automatic negotiation of protocols; there's no need for URL prefixing to determine WebSocket endpoints versus HTTP endpoints.

Running

Simply point Daphne to your ASGI application, and optionally set a bind address and port (defaults to localhost, port 8000):

daphne -b 0.0.0.0 -p 8001 django_project.asgi:application

If you intend to run daphne behind a proxy server you can use UNIX sockets to communicate between the two:

daphne -u /tmp/daphne.sock django_project.asgi:application

If daphne is being run inside a process manager, you might want it to bind to a file descriptor passed down from a parent process. To achieve this you can use the --fd flag:

daphne --fd 5 django_project.asgi:application

If you want more control over the port/socket bindings you can fall back to using twisted's endpoint description strings by using the --endpoint (-e) flag, which can be used multiple times. This line would start a SSL server on port 443, assuming that key.pem and crt.pem exist in the current directory (requires pyopenssl to be installed):

daphne -e ssl:443:privateKey=key.pem:certKey=crt.pem django_project.asgi:application

Endpoints even let you use the txacme endpoint syntax to get automatic certificates from Let's Encrypt, which you can read more about at http://txacme.readthedocs.io/en/stable/.

To see all available command line options run daphne with the -h flag.

View on GitHub

2.    websockify

websockify was formerly named wsproxy and was part of the noVNC project.

At the most basic level, websockify just translates WebSockets traffic to normal socket traffic. Websockify accepts the WebSockets handshake, parses it, and then begins forwarding traffic between the client and the target in both directions.

News/help/contact

Notable commits, announcements and news are posted to @noVNC

If you are a websockify developer/integrator/user (or want to be) please join the noVNC/websockify discussion group

Bugs and feature requests can be submitted via github issues.

If you want to show appreciation for websockify you could donate to a great non-profits such as: Compassion International, SIL, Habitat for Humanity, Electronic Frontier Foundation, Against Malaria Foundation, Nothing But Nets, etc. Please tweet @noVNC if you do.

WebSockets binary data

Starting with websockify 0.5.0, only the HyBi / IETF 6455 WebSocket protocol is supported. There is no support for the older Base64 encoded data format.

Encrypted WebSocket connections (wss://)

To encrypt the traffic using the WebSocket 'wss://' URI scheme you need to generate a certificate and key for Websockify to load. By default, Websockify loads a certificate file name self.pem but the --cert=CERT and --key=KEY options can override the file name. You can generate a self-signed certificate using openssl. When asked for the common name, use the hostname of the server where the proxy will be running:

openssl req -new -x509 -days 365 -nodes -out self.pem -keyout self.pem

For a self-signed certificate to work, you need to make your client/browser understand it. You can do this by installing it as accepted certificate, or by using that same certificate for a HTTPS connection to which you navigate first and approve. Browsers generally don't give you the "trust certificate?" prompt by opening a WSS socket with invalid certificate, hence you need to have it accept it by either of those two methods.

If you have a commercial/valid SSL certificate with one or more intermediate certificates, concat them into one file, server certificate first, then the intermediate(s) from the CA, etc. Point to this file with the --cert option and then also to the key with --key. Finally, use --ssl-only as needed.

View on GitHub

3.    Flask-Sockets

Elegant WebSockets for your Flask apps.

Simple usage of route decorator:

from flask import Flask
from flask_sockets import Sockets


app = Flask(__name__)
sockets = Sockets(app)


@sockets.route('/echo')
def echo_socket(ws):
    while not ws.closed:
        message = ws.receive()
        ws.send(message)


@app.route('/')
def hello():
    return 'Hello World!'


if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()

Usage of Flask blueprints:

from flask import Flask, Blueprint
from flask_sockets import Sockets


html = Blueprint(r'html', __name__)
ws = Blueprint(r'ws', __name__)


@html.route('/')
def hello():
    return 'Hello World!'

@ws.route('/echo')
def echo_socket(socket):
    while not socket.closed:
        message = socket.receive()
        socket.send(message)


app = Flask(__name__)
sockets = Sockets(app)

app.register_blueprint(html, url_prefix=r'/')
sockets.register_blueprint(ws, url_prefix=r'/')


if __name__ == "__main__":
    from gevent import pywsgi
    from geventwebsocket.handler import WebSocketHandler
    server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
    server.serve_forever()

Combining WebSockets with Ajax (XHR) endpoints also comes handy with the support of session handling built-in to sockets as well. As an example you could use an Ajax login call which would create a new session and accordingly set a secure HttpOnly cookie to the browser. After authorization, you can connect to the WebSocket endpoint and reuse the session handling from Flask there as well (as shown here: https://pythonhosted.org/Flask-Session/). Access to other custom cookies is also possible via Flasks request.cookies property.

View on GitHub

4.   gevent-socketio
 

gevent-socketio is a Python implementation of the Socket.IO protocol, developed originally for Node.js by LearnBoost and then ported to other languages. Socket.IO enables real-time web communications between a browser and a server, using a WebSocket-like API. One aim of this project is to provide a single gevent-based API that works across the different WSGI-based web frameworks out there (Pyramid, Pylons, Flask, web2py, Django, etc...). Only ~3 lines of code are required to tie-in gevent-socketio in your framework. Note: you need to use the gevent python WSGI server to use gevent-socketio.

Community, rise up!

ANNOUNCEMENT: This project is in need of a solid maintainer to navigate through the 27+ open Pull Requests, merge what needs to be merged, and continue on with newer developments. @abourget is not putting as much time as he'd like on this project these days. This project has nearly 1000 GitHub Stars.. it's used by major corporations. It's a great project for you to lead. Contact me on Twitter @bourgetalexndre to take more leadership.

Technical overview

Most of the gevent-socketio implementation is pure Python. There is an obvious dependency on gevent, and another on gevent-websocket. There are integration examples for Pyramid, Flask, Django and BYOF (bring your own framework!).

View on GitHub

5.    SockJS-tornado server

SockJS-tornado is a Python server side counterpart of SockJS-client browser library running on top of Tornado framework.

Simplified echo SockJS server could look more or less like::

from tornado import web, ioloop from sockjs.tornado import SockJSRouter, SockJSConnection

class EchoConnection(SockJSConnection):

def on_message(self, msg):

self.send(msg)

if __name__ == '__main__':

EchoRouter = SockJSRouter(EchoConnection, '/echo')

app = web.Application(EchoRouter.urls) app.listen(9999) ioloop.IOLoop.instance().start()

(Take look at examples for a complete version).

Subscribe to SockJS mailing list for discussions and support.

Settings

You can pass various settings to the SockJSRouter, in a dictionary:

MyRouter = SockJSRouter(MyConnection, '/my', dict(disabled_transports=['websocket']))

Deployment

sockjs-tornado properly works behind haproxy and it is recommended deployment approach.

Sample configuration file can be found here.

If your log is full of "WARNING: Connection closed by the client", pass no_keep_alive as True to HTTPServer constructor:

HTTPServer(app, no_keep_alive=True).listen(port)

or:

app.listen(port, no_keep_alive=True)

View on GitHub

6.    TornadIO2

This is python server implementation of the Socket.IO realtime transport library on top of the Tornado framework.

TornadIO2 is compatible with 0.7+ version of the Socket.IO and implements most of the features found in original Socket.IO server software.

Key features:

  • Supports Socket.IO 0.8 protocol and related features
  • Full unicode support
  • Support for generator-based asynchronous code (tornado.gen API)
  • Statistics capture (packets per second, etc)

What is Socket.IO?

Socket.IO aims to make realtime apps possible in every browser and mobile device, blurring the differences between the different transport mechanisms. It's care-free realtime 100% in JavaScript.

You can use it to build push service, games, etc. Socket.IO will adapt to the clients browser and will use most effective transport protocol available.

Getting Started

In order to start working with the TornadIO2 library, you have to have some basic Tornado knowledge. If you don't know how to use it, please read Tornado tutorial, which can be found here.

If you're familiar with Tornado, do following to add support for Socket.IO to your application:

  1. Derive from tornadio2.SocketConnection class and override on_message method (on_open/on_close are optional):
class MyConnection(tornadio2.SocketConnection):
    def on_message(self, message):
        pass

2.   Create TornadIO2 server for your connection:

MyRouter = tornadio2.TornadioRouter(MyConnection)

3.   Add your handler routes to the Tornado application:

application = tornado.web.Application(
    MyRouter.urls,
    socket_io_port = 8000)

4.   Start your application

5.   You have your socket.io server running at port 8000. Simple, right?

View on GitHub


Related videos:

WebSockets with Python and WebSocket API

Related posts:

#python #websocket 

7 Most Popular Websocket Utilities Libraries In Python
Ssekidde  Nat

Ssekidde Nat

1662719640

5 Best Websocket Utilities Libraries with Python for Developers

In this Python and GraphQL article, we learn about GraphQL Utilities: 5 Best Websocket Utilities Libraries with Python for Developers

  1. websocket-client: WebSocket client for Python
  2. websockets: Library for building WebSocket servers and clients in Python
  3. Autobahn-Python: WebSocket and WAMP in Python for Twisted and asyncio
  4. Flask-SocketIO: Socket.IO integration for Flask applications.
  5. python-socketio: Python Socket.IO server and client

 

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

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

What is a WebSocket in Python?

Kết quả hình ảnh cho what is Websocket Utilities in python

websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance. Built on top of asyncio , Python's standard asynchronous I/O framework, it provides an elegant coroutine-based API.

5 Best Websocket Utilities Libraries with Python for Developers

1.websocket-client

websocket-client is a WebSocket client for Python. It provides access to low level APIs for WebSockets. websocket-client implements version hybi-13 of the WebSocket protocol. This client does not currently support the permessage-deflate extension from RFC 7692.

Installation

You can use either python3 setup.py install or pip3 install websocket-client to install. This module is tested on Python 3.7+.

There are several optional dependencies that can be installed to enable specific websocket-client features.

  • To install python-socks for proxy usage and wsaccel for a minor performance boost, use: pip3 install websocket-client[optional]
  • To install websockets to run unit tests using the local echo server, use: pip3 install websocket-client[test]
  • To install Sphinx and sphinx_rtd_theme to build project documentation, use: pip3 install websocket-client[docs]

While not a strict dependency, rel is useful when using run_forever with automatic reconnect. Install rel with pip3 install rel.

Footnote: Some shells, such as zsh, require you to escape the [ and ] characters with a \.

View on GitHub

2.    websockets

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

Built on top of asyncio, 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 python

import asyncio
from websockets import connect

async def hello(uri):
    async with connect(uri) as websocket:
        await websocket.send("Hello world!")
        await websocket.recv()

asyncio.run(hello("ws://localhost:8765"))

And here's an echo server:

#!/usr/bin/env python

import asyncio
from websockets import serve

async def echo(websocket):
    async for message in websocket:
        await websocket.send(message)

async def main():
    async with serve(echo, "localhost", 8765):
        await asyncio.Future()  # run forever

asyncio.run(main())

View on GitHub

3.   autobahn-python
 

WebSocket & WAMP for Python on Twisted and asyncio.

Introduction

Autobahn|Python is a subproject of Autobahn and provides open-source implementations of

for Python 3.7+ and running on Twisted and asyncio.

You can use Autobahn|Python to create clients and servers in Python speaking just plain WebSocket or WAMP.

WebSocket allows bidirectional real-time messaging on the Web and beyond, while WAMP adds real-time application communication on top of WebSocket.

WAMP provides asynchronous Remote Procedure Calls and Publish & Subscribe for applications in one protocol running over WebSocket. WAMP is a routed protocol, so you need a WAMP Router to connect your Autobahn|Python based clients. We provide Crossbar.io, but there are other options as well.

Note

Autobahn|Python up to version v19.11.2 supported Python 2 and 3.4+, and up to version v20.7.1 supported Python 3.5+, and up to version v21.2.1 supported Python 3.6+.

Show me some code

To give you a first impression, here are two examples. We have lot more in the repo.

WebSocket Echo Server

Here is a simple WebSocket Echo Server that will echo back any WebSocket message received:

from autobahn.twisted.websocket import WebSocketServerProtocol
# or: from autobahn.asyncio.websocket import WebSocketServerProtocol

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {} bytes".format(len(payload)))
        else:
            print("Text message received: {}".format(payload.decode('utf8')))

        # echo back message verbatim
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {}".format(reason))

To actually run above server protocol, you need some lines of boilerplate.

View on GitHub

4.    Flask-SocketIO

Socket.IO integration for Flask applications.

Installation

You can install this package as usual with pip:

pip install flask-socketio

Example

from flask import Flask, render_template
from flask_socketio import SocketIO, emit
    
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.event
def my_event(message):
    emit('my response', {'data': 'got it!'})

if __name__ == '__main__':
    socketio.run(app)

View on GitHub

5.   python-socketio

Python implementation of the Socket.IO_ realtime client and server.

Version compatibility

The Socket.IO protocol has been through a number of revisions, and some of these introduced backward incompatible changes, which means that the client and the server must use compatible versions for everything to work.

If you are using the Python client and server, the easiest way to ensure compatibility is to use the same version of this package for the client and the server. If you are using this package with a different client or server, then you must ensure the versions are compatible.

The version compatibility chart below maps versions of this package to versions of the JavaScript reference implementation and the versions of the Socket.IO and Engine.IO protocols.

JavaScript Socket.IO versionSocket.IO protocol revisionEngine.IO protocol revisionpython-socketio version
0.9.x1, 21, 2Not supported
1.x and 2.x3, 434.x
3.x and 4.x545.x

View on GitHub


Related videos:

Connect to WebSocket API using Python

Related posts:

#python #websocket 

5 Best Websocket Utilities Libraries with Python for Developers

High-performance Web Rendering Engine, Built on Flutter

kraken_websocket

W3C compact WebSocket API support.

Installation

First, add kraken_websocket as a dependency in your pubspec.yaml file.

Second, add the following code before calling runApp():

import 'package:kraken_websocket/kraken_websocket.dart';
void main() {
  runApp(MyApp());
  KrakenWebsocket.initialize();
}

Example

let ws = new WebSocket('ws://127.0.0.1:8399');
ws.onopen = () => {
    ws.send('helloworld');
};
ws.onmessage = (event) => {
    console.log(event);
}

Contribute

convert javascript code to quickjs bytecode:

kraken qjsc ./lib/websocket.js ./lib/websocket_qjsc.dart --dart

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add kraken_websocket

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  kraken_websocket: ^2.0.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:kraken_websocket/kraken_websocket.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:kraken_websocket/kraken_websocket.dart';
import 'package:kraken/kraken.dart';

void main() {
  runApp(MyApp());
  KrakenWebsocket.initialize();
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(
            title: const Text('Plugin example app'),
          ),
          body: Kraken(
            bundle: KrakenBundle.fromUrl('assets://assets/bundle.js'),
          )),
    );
  }
} 

Download Details:

Author: 

Source Code: https://pub.dev/packages/kraken_websocket/

#websocket #flutter 

High-performance Web Rendering Engine, Built on Flutter
Hunter  Krajcik

Hunter Krajcik

1661293620

A Flutter Plugin for Websockets on Android (currently)

Websocket support  

A Flutter plugin for websockets on Android (currently). This plugin is based on okHttp (for Android platform).

Plugin was created as an attempt to overcome shortcomings of Flutter standard WebSocket implementation (cookbook) like connection not staying open while screen is locked or the application is in background. This plugin solves these problems.

Introduction

Websocket support uses Platform Channel to expose Dart APIs that Flutter application can use to communicate with platform specific websocket native libraries. For andorid, chosen java Websocket implementation is OkHttp.

Example

// WebSocketConnection will be obtained via _onWsOpen callback in WebSocketClient
WebSocketConnection _webSocketConnection;

// instantiate WebSocketClient with DefaultWebSocketListener and some callbacks
// Of course you can use you own WebSocketListener implementation
final WebSocketClient _wsClient = WebSocketClient(DefaultWebSocketListener.forTextMessages(
        (wsc) => _webSocketConnection = wsc,                       // _onWsOpen callback
        (code, msg) => print('Connection closed. Resaon: $msg'),  // _onWsClosed callback
        (msg) => print('Message received: $msg')));               // _onStringMessage callback
// ...
// connect to remote ws endpoint
await _wsClient.connect("ws://echo.websocket.org");

// ...
// After connection is established, use obtained WebSocketConnection instance to send messages
_webSocketConnection.sendTextMessage('Hello from Websocket support');

or see /example/lib/main.dart

Build Dependencies

  • Dart SDK version: >=2.12.0 <3.0.0
  • Flutter SDK version: >=1.20.0
  • Java version: 11
  • AGP version: 7.2.x
  • Gradle version: 7.4.2
  • Android SDK min version: 21
  • Android SDK target version: 32

TODO

Unfortunately, iOS implementation is still missing. So, if you have know-how, and you're willing to implement it - you will be more than welcomed. Preffered WebSocket libs are NWWebSocket and Starscream, but we are opened for other options as well.

Contributing

See the Contributing guide for details on contributing to this project.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add web_socket_support

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  web_socket_support: ^0.2.3

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:web_socket_support/web_socket_support.dart';

example/lib/main.dart

// coverage:ignore-file
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:web_socket_support/web_socket_support.dart';

// ignore_for_file: avoid_print
void main() {
  final backend = WsBackend();
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider<WsBackend>.value(
          value: backend,
        ),
        ChangeNotifierProvider<WebSocketSupport>(
          create: (ctx) => WebSocketSupport(backend),
        ),
      ],
      child: const WebSocketSupportExampleApp(),
    ),
  );
}

// TestApp use this ChangeNotifier to listen for changes regarding message list
class WsBackend with ChangeNotifier {
  final textController = TextEditingController();
  final List<ServerMessage> _messages = [];

  WsBackend() {
    print('WsBackend created.');
  }

  void addMesage(ServerMessage msg) {
    _messages.add(msg);
    notifyListeners();
  }

  void clearMesages() {
    _messages.clear();
    notifyListeners();
  }

  List<ServerMessage> getMessages() {
    return List.unmodifiable(_messages);
  }

  bool hasMessages() {
    return _messages.isNotEmpty;
  }

  @override
  void dispose() {
    textController.dispose();
    super.dispose();
  }
}

// TestApp use this ChangeNotifier to listen for connection status changes
class WebSocketSupport with ChangeNotifier {
  static const String serverUrl = 'ws://ws.ifelse.io';

  final WsBackend _backend;

  // locals
  late WebSocketClient _wsClient;
  WebSocketConnection? _webSocketConnection;
  bool working = false;

  WebSocketSupport(this._backend) {
    _wsClient = WebSocketClient(DefaultWebSocketListener.forTextMessages(
      _onWsOpened,
      _onWsClosed,
      _onTextMessage,
      (_, __) => {},
      _onError,
    ));
    print('WebSocketSupport created.');
  }

  void _onWsOpened(WebSocketConnection webSocketConnection) {
    _webSocketConnection = webSocketConnection;
    working = false;
    notifyListeners();
  }

  void _onWsClosed(int code, String reason) {
    _webSocketConnection = null;
    _backend.clearMesages();
    working = false;
    notifyListeners();
  }

  void _onTextMessage(String message) {
    _backend.addMesage(ServerMessage(message, DateTime.now()));
    notifyListeners();
  }

  void _onError(Exception ex) {
    print('_onError: Fatal error occured: $ex');
    _webSocketConnection = null;
    working = false;
    _backend.addMesage(
        ServerMessage('Error occured on WS connection!', DateTime.now()));
    notifyListeners();
  }

  bool isConnected() {
    return _webSocketConnection != null;
  }

  void sendMessage() {
    if (_webSocketConnection != null) {
      _webSocketConnection?.sendStringMessage(_backend.textController.text);
      _backend.textController.clear();
    }
  }

  Future<void> connect() async {
    working = true;
    _backend.textController.clear();
    _backend.clearMesages();
    try {
      await _wsClient.connect(serverUrl);
      notifyListeners();
    } on PlatformException catch (e) {
      final errorMsg = 'Failed to connect to ws server. Error:$e';
      print(errorMsg);
      _backend.addMesage(ServerMessage(errorMsg, DateTime.now()));
    }
  }

  Future<void> disconnect() async {
    working = true;
    await _wsClient.disconnect();
    notifyListeners();
  }
}

// ExampleApp uses WebSocketSupport to communicate with remote ws server
// App is able to send arbitrary text messages to remote echo server
// and will keep all remote servers replys in list as long as ws session is up.
class WebSocketSupportExampleApp extends StatelessWidget {
  const WebSocketSupportExampleApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('WebSocketSupport example app'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: const <Widget>[
            WsControlPanel(),
            WsTextInput(),
            WsMessages(),
          ],
        ),
      ),
    );
  }
}

class WsControlPanel extends StatelessWidget {
  const WsControlPanel({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        const SizedBox(height: 10),
        Center(
          child: Consumer<WebSocketSupport>(builder: (ctx, ws, _) {
            return Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 10, right: 10),
                  child: Row(
                    children: [
                      // status title
                      const Text('WS status:'),
                      Padding(
                        padding: const EdgeInsets.only(left: 5, right: 5),
                        child: Icon(
                          ws.isConnected()
                              ? Icons.check_circle_outlined
                              : Icons.highlight_off,
                          color: _connectionColor(ws),
                          size: 20,
                        ),
                      ),
                      //status value
                      Text(
                        (ws.isConnected() ? 'Connected' : 'Disconnected'),
                        style: TextStyle(color: _connectionColor(ws)),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 10, right: 10),
                  child: ElevatedButton(
                    key: const Key('connect'),
                    onPressed: ws.working
                        ? null
                        : () async {
                            ws.isConnected()
                                ? await ws.disconnect()
                                : await ws.connect();
                          },
                    child: ws.isConnected()
                        ? const Text('Disconnect')
                        : const Text('Connect'),
                  ),
                ),
              ],
            );
          }),
        ),
        const Divider(),
      ],
    );
  }

  MaterialColor _connectionColor(WebSocketSupport ws) =>
      ws.isConnected() ? Colors.green : Colors.red;
}

class WsTextInput extends StatelessWidget {
  const WsTextInput({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<WebSocketSupport>(builder: (ctx, ws, _) {
      return !ws.isConnected()
          ? const SizedBox.shrink()
          : Column(
              children: [
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: TextField(
                          key: const Key('textField'),
                          textAlign: TextAlign.center,
                          controller:
                              Provider.of<WsBackend>(context, listen: false)
                                  .textController,
                          decoration: const InputDecoration(
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Colors.greenAccent, width: 2.0),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderSide:
                                  BorderSide(color: Colors.blue, width: 2.0),
                            ),
                            hintText: 'Enter message to send to server',
                          ),
                        ),
                      ),
                      IconButton(
                        key: const Key('sendButton'),
                        icon: const Icon(Icons.send),
                        onPressed: () => ws.sendMessage(),
                      ),
                    ],
                  ),
                ),
                const Divider(),
              ],
            );
    });
  }
}

class WsMessages extends StatelessWidget {
  const WsMessages({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<WsBackend>(builder: (ctx, be, _) {
      return be.getMessages().isEmpty
          ? const SizedBox.shrink()
          : Expanded(
              child: Column(
                children: [
                  const Padding(
                    padding: EdgeInsets.only(top: 10, bottom: 10),
                    child: Text(
                      'Reply messages from: ${WebSocketSupport.serverUrl}',
                      key: Key('replyHeader'),
                    ),
                  ),
                  Expanded(
                    child: ListView.separated(
                      itemCount: be.getMessages().length,
                      separatorBuilder: (BuildContext context, int index) =>
                          const Divider(),
                      itemBuilder: (BuildContext context, int index) {
                        var message = be.getMessages()[index];
                        return ListTile(
                          title: Text(
                            '${DateFormat.Hms().format(message.dateTime)}: ${message.message}',
                            key: Key(message.message),
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            );
    });
  }
}

class ServerMessage {
  final String message;
  final DateTime dateTime;

  ServerMessage(this.message, this.dateTime);
}

Download Details:

Author: Sharpbitstudio
Source Code: https://github.com/sharpbitstudio/flutter-websocket-support-mobile-implementation 
License: BSD-3-Clause license

#flutter #dart #websocket 

A Flutter Plugin for Websockets on Android (currently)

Simple Development Server with Live-reload Capability for Julia

Live Server for Julia  

This is a simple and lightweight development web-server written in Julia, based on HTTP.jl. It has live-reload capability, i.e. when modifying a file, every browser (tab) currently displaying the corresponding page is automatically refreshed.

LiveServer is inspired from Python's http.server and Node's browsersync.

Installation

To install it in Julia ≥ 1.3, use the package manager with

pkg> add LiveServer

For Julia [1.0, 1.3), you can use LiveServer's version 0.7.4:

pkg> add LiveServer@0.7.4

Make it a shell command

LiveServer is a small package and fast to load with one main functionality (serve), it can be convenient to make it a shell command: (I'm using the name lss here but you could use something else):

alias lss='julia -e "import LiveServer as LS; LS.serve(launch_browser=true)"'

you can then use lss in any directory to show a directory listing in your browser, and if the directory has an index.html then that will be rendered in your browser.

Usage

The main function LiveServer exports is serve which starts listening to the current folder and makes its content available to a browser. The following code creates an example directory and serves it:

julia> using LiveServer
julia> LiveServer.example() # creates an "example/" folder with some files
julia> cd("example")
julia> serve() # starts the local server & the file watching
✓ LiveServer listening on http://localhost:8000/ ...
  (use CTRL+C to shut down)

Open a Browser and go to http://localhost:8000/ to see the content being rendered; try modifying files (e.g. index.html) and watch the changes being rendered immediately in the browser.

In the REPL:

julia> using LiveServer
julia> serve(host="0.0.0.0", port=8001, dir=".") # starts the remote server & the file watching
✓ LiveServer listening on http://0.0.0.0:8001...
  (use CTRL+C to shut down)

In the terminal:

julia -e 'using LiveServer; serve(host="0.0.0.0", port=8001, dir=".")'

Open a browser and go to https://localhost:8001/ to see the rendered content of index.html or, if it doesn't exist, the content of the directory. You can set the port to a custom number. This is similar to the http.server in Python.

Serve docs

servedocs is a convenience function that runs Documenter along with LiveServer to watch your doc files for any changes and render them in your browser when modifications are detected.

Assuming you are in directory/to/YourPackage.jl, that you have a docs/ folder as prescribed by Documenter.jl and LiveServer installed in your global environment, you can run:

$ julia

pkg> activate docs

julia> using YourPackage, LiveServer

julia> servedocs()
[ Info: SetupBuildDirectory: setting up build directory.
[ Info: ExpandTemplates: expanding markdown templates.
...
└ Deploying: ✘
✓ LiveServer listening on http://localhost:8000/ ...
  (use CTRL+C to shut down)

Open a browser and go to http://localhost:8000/ to see your docs being rendered; try modifying files (e.g. docs/index.md) and watch the changes being rendered in the browser.

To run the server with one line of code, run:

$ julia --project=docs -ie 'using YourPackage, LiveServer; servedocs()'

Note: this works with Literate.jl as well. See the docs.

Download Details:

Author: tlienart
Source Code: https://github.com/tlienart/LiveServer.jl 
License: View license

#julia #webserver #websocket 

Simple Development Server with Live-reload Capability for Julia
Nat  Grady

Nat Grady

1660217160

Httpuv: HTTP and WebSocket Server Package for R

httpuv: HTTP and WebSocket server library for R

httpuv provides low-level socket and protocol support for handling HTTP and WebSocket requests directly from within R. It uses a multithreaded architecture, where I/O is handled on one thread, and the R callbacks are handled on another.

It is primarily intended as a building block for other packages, rather than making it particularly easy to create complete web applications using httpuv alone. httpuv is built on top of the libuv and http-parser C libraries, both of which were developed by Joyent, Inc.

Installing

You can install the stable version from CRAN, or the development version using remotes:

# install from CRAN
install.packages("httpuv")

# or if you want to test the development version here
if (!require("remotes")) install.packages("remotes")
remotes::install_github("rstudio/httpuv")

Since httpuv contains C code, you'll need to make sure you're set up to install packages with compiled code. Follow the instructions at http://www.rstudio.com/ide/docs/packages/prerequisites

Basic Usage

This is a basic web server that listens on port 8080 and responds to HTTP requests with a web page containing the current system time and the path of the request:

library(httpuv)

s <- startServer(host = "0.0.0.0", port = 8080,
  app = list(
    call = function(req) {
      body <- paste0("Time: ", Sys.time(), "<br>Path requested: ", req$PATH_INFO)
      list(
        status = 200L,
        headers = list('Content-Type' = 'text/html'),
        body = body
      )
    }
  )
)

Note that when host is 0.0.0.0, it listens on all network interfaces. If host is 127.0.0.1, it will only listen to connections from the local host.

The startServer() function takes an app object, which is a named list with functions that are invoked in response to certain events. In the example above, the list contains a function call. This function is invoked when a complete HTTP request is received by the server, and it is passed an environment object req, which contains information about HTTP request. req$PATH_INFO is the path requested (if the request was for http://127.0.0.1:8080/foo, it would be "/foo").

The call function is expected to return a list containing status, headers, and body. That list will be transformed into a HTTP response and sent to the client.

To stop the server:

s$stop()

Or, to stop all running httpuv servers:

stopAllServers()

Static paths

A httpuv server application can serve up files on disk. This happens entirely within the I/O thread, so doing so will not block or be blocked by activity in the main R thread.

To serve a path, use staticPaths in the app. This will serve the www/ subdirectory of the current directory (from when startServer is called) as the root of the web path:

s <- startServer("0.0.0.0", 8080,
  app = list(
    staticPaths = list("/" = "www/")
  )
)

By default, if a file named index.html exists in the directory, it will be served when / is requested.

staticPaths can be combined with call. In this example, the web paths /assets and /lib are served from disk, but requests for any other paths go through the call function.

s <- startServer("0.0.0.0", 8080,
  list(
    call = function(req) {
      list(
        status = 200L,
        headers = list(
          'Content-Type' = 'text/html'
        ),
        body = "Hello world!"
      )
    },
    staticPaths = list(
      "/assets" = "content/assets/",
      # Don't use index.html for /lib
      "/lib" = staticPath("content/lib", indexhtml = FALSE)
    )
  )
)

WebSocket server

httpuv also can handle WebSocket connections. For example, this app acts as a WebSocket echo server:

s <- startServer("127.0.0.1", 8080,
  list(
    onWSOpen = function(ws) {
      # The ws object is a WebSocket object
      cat("Server connection opened.\n")

      ws$onMessage(function(binary, message) {
        cat("Server received message:", message, "\n")
        ws$send(message)
      })
      ws$onClose(function() {
        cat("Server connection closed.\n")
      })
    }
  )
)

To test it out, you can connect to it using the websocket package (which provides a WebSocket client). You can do this from the same R process or a different one.

ws <- websocket::WebSocket$new("ws://127.0.0.1:8080/")
ws$onMessage(function(event) {
  cat("Client received message:", event$data, "\n")
})

# Wait for a moment before running next line
ws$send("hello world")

# Close client
ws$close()

Note that both the httpuv and websocket packages provide a class named WebSocket; however, in httpuv, that class acts as a server, and in websocket, it acts as a client. They also have different APIs. For more information about the WebSocket client package, see the project page.


Debugging builds

httpuv can be built with debugging options enabled. This can be done by uncommenting these lines in src/Makevars, and then installing. The first one enables thread assertions, to ensure that code is running on the correct thread; if not. The second one enables tracing statements: httpuv will print lots of messages when various events occur.

PKG_CPPFLAGS += -DDEBUG_THREAD -UNDEBUG
PKG_CPPFLAGS += -DDEBUG_TRACE

To install it directly from GitHub with these options, you can use with_makevars, like this:

withr::with_makevars(
  c(PKG_CPPFLAGS="-DDEBUG_TRACE -DDEBUG_THREAD -UNDEBUG"), {
    devtools::install_github("rstudio/httpuv")
  }, assignment = "+="
)

© 2013-2020 RStudio, Inc.

Download Details:

Author: rstudio
Source Code: https://github.com/rstudio/httpuv 
License: View license

#r #http #websocket 

Httpuv: HTTP and WebSocket Server Package for R
Thierry  Perret

Thierry Perret

1659461040

Comment Implémenter Une Connexion WebSocket à L'aide De NodeJS

WebSocket est un protocole de communication informatique qui vous offre un canal de communication bidirectionnel entre un client et un serveur.

C'est assez différent du protocole HTTP qui est utilisé comme protocole de communication standard dans le navigateur.

Avec une connexion WebSocket, le serveur peut envoyer des messages au client sans attendre une demande du client. En connexion HTTP, une requête doit être initiée par le client.

Une fois qu'une connexion WebSocket a été établie entre le client et le serveur, le canal WebSocket sera maintenu ouvert en arrière-plan afin que la communication ait une surcharge et une latence plus faibles par rapport à la connexion HTTP.

Tout comme vous pouvez créer un serveur HTTP pour recevoir des requêtes HTTP, vous pouvez également créer un serveur WebSocket pour établir des connexions WebSocket à l'aide de NodeJS.

Ce tutoriel vous aidera à apprendre à créer votre propre serveur WebSocket avec NodeJS

Le code d'implémentation complet peut être trouvé dans ce référentiel node-websocket-example .

Créer un serveur WebSocket dans NodeJS

Pour créer un serveur WebSocket dans NodeJS, vous pouvez utiliser le module ws , qui est l'implémentation WebSocket la plus largement utilisée pour NodeJS.

Tout d'abord, vous devez installer le wsmodule sur votre projet :

npm install ws
# or
yarn add ws

Une fois le module installé, vous pouvez immédiatement créer un index.jsfichier dans lequel vous créez un nouveau serveur WebSocket.

Tout d'abord, importez le wsmodule et ouvrez une connexion au serveur WebSocket sur un port spécifique. Je vais utiliser le port 8080 dans l'exemple ci-dessous :

const WebSocket = require("ws");

const wss = new WebSocket.Server({ port: 8080 });

Ensuite, écrivez le code pour permettre à votre serveur Websocket d'envoyer un message au client lorsqu'une connexion a été établie.

Vous devez écouter l' connectionévénement WebSocket et send()un message lorsqu'une connexion a été établie :

wss.on("connection", (ws) => {
  // A connection has been made
  // send back a message
  ws.send("Hi client! You are now connected to me!");
});

Enfin, vous devez également écouter l' messageévénement, qui sera déclenché chaque fois que le client enverra un message au serveur comme suit :

wss.on("connection", (ws) => {
  // A connection has been made
  // send back a message
  ws.send("Hi client! You are now connected to me!");

  // listen to the message event
  // then log the received message
  ws.on("message", (message) => {
    console.log("New message from client: %s", message);
  });
});

Et c'est tout ce dont vous avez besoin pour créer un serveur WebSocket à l'aide de NodeJS. Créons un client WebSocket pour se connecter à votre wsserveur depuis le navigateur.

Connexion à un WebSocket depuis le navigateur.

Les navigateurs Web les plus populaires tels que Chrome, Safari et Firefox implémentent déjà une API JavaScript WebSocket native que vous pouvez utiliser pour vous connecter à un serveur WebSocket.

Essayons de nous connecter au serveur WebSocket avec un simple fichier HTML.

Tout d'abord, créez un index.htmlfichier avec le <body>contenu suivant :

<body>
  <h1>WebSocket Client Implementation</h1>
  <button id="wsConnect">Connect to WebSocket</button>
</body>

Ensuite, ajoutez un écouteur d'événement à l' <button>élément qui écoutera l' clickévénement.

L'écouteur d'événement exécutera une fonction qui ouvre une connexion à votre serveur WebSocket :

const button = document.querySelector("#wsConnect");
button.addEventListener("click", () => {
  const url = "ws://localhost:8080";
  const wsClient = new WebSocket(url);
});

Le constructeur new WebSocket()renverra un nouvel objet WebSocket à partir duquel vous pourrez écouter les événements liés à WebSocket.

Par exemple, vous pouvez écouter la WebSocket.onopenpropriété, qui est un gestionnaire d'événements qui se déclenche lorsque la connexion est prête à envoyer et recevoir des données :

const button = document.querySelector("#wsConnect");
button.addEventListener("click", () => {
  const url = "ws://localhost:8080";
  const wsClient = new WebSocket(url);

  wsClient.onopen = () => {
    console.log(`Connection to ${url} has been established`);
  };
});

Ensuite, vous pouvez également écouter le onmessagegestionnaire d'événements, qui se déclenche lorsque le client reçoit un message :

wsClient.onmessage = (e) => {
  console.log(e.data);
};

Enfin, vous pouvez également ajouter un écouteur pour la onerrorpropriété. Il est appelé lorsque la connexion WebSocket rencontre une erreur :

wsClient.onerror = (err) => {
  console.log(`WebSocket error: ${err}`);
};

Voici le code complet de la page HTML pour tester les connexions WebSocket :

<body>
  <h1>WebSocket Client Implementation</h1>
  <button id="wsConnect">Connect to WebSocket</button>
  <script>
    const button = document.querySelector("#wsConnect");
    button.addEventListener("click", () => {
      const url = "ws://localhost:8080";
      const wsClient = new WebSocket(url);

      wsClient.onopen = () => {
        console.log(`Connection to ${url} has been established`);
      };

      // receive message from the server
      wsClient.onmessage = (e) => {
        console.log(e.data);
      };

      // Log WebSocket error events
      wsClient.onerror = (err) => {
        console.log(`WebSocket error: ${err}`);
      };
    });
  </script>
</body>

Pour la liste complète des propriétés de l'objet WebSocket, vous pouvez consulter la documentation MDN WebSocket .

Il est temps de tester votre implémentation WebSocket. Ouvrez le index.htmlfichier depuis votre navigateur et cliquez sur le bouton.

Vous verrez les journaux de la console du navigateur comme suit :

Sortie du client de navigateur WebSocket

Sortie du client de navigateur WebSocket

Vous avez établi avec succès une connexion WebSocket entre le serveur NodeJS et le navigateur ! Essayez d'envoyer un message au serveur à partir de la onopenfonction de gestionnaire :

wsClient.onopen = () => {
  console.log(`Connection to ${url} has been established`);
  wsClient.send("Hello World!");
};

Vous verrez le texte consigné depuis la console NodeJS :

Sortie du serveur WebSocket NodeJS

Sortie du serveur WebSocket NodeJS

Vous venez d'apprendre à implémenter des connexions WebSocket à l'aide de NodeJS et du navigateur. Bon travail! 😉

Pour faire de l'exercice, essayez d'ajouter un formulaire avec un <input>élément de texte et un bouton d'envoi. Vous pouvez envoyer le message au serveur en utilisant la WebSocket.send()méthode chaque fois que vous cliquez sur le bouton Soumettre.

Lien : https://sebhastian.com/node-websocket/

#websocket #noeud #nodejs

Comment Implémenter Une Connexion WebSocket à L'aide De NodeJS

Как реализовать соединение WebSocket с помощью NodeJS

WebSocket — это протокол компьютерной связи, который предлагает вам двусторонний канал связи между клиентом и сервером.

Он сильно отличается от протокола HTTP, который используется в качестве стандартного протокола связи в браузере.

С помощью соединения WebSocket сервер может отправлять сообщения клиенту, не дожидаясь запроса клиента. В HTTP-соединении запрос должен быть инициирован клиентом.

После того как соединение WebSocket установлено между клиентом и сервером, канал WebSocket будет оставаться открытым в фоновом режиме, так что связь будет иметь меньшие накладные расходы и задержку по сравнению с HTTP-соединением.

Точно так же, как вы можете создать HTTP-сервер для получения HTTP-запросов, вы также можете создать сервер WebSocket для установления соединений WebSocket с помощью NodeJS.

Это руководство поможет узнать, как создать собственный сервер WebSocket с помощью NodeJS.

Полный код реализации можно найти в этом репозитории node-websocket-example .

Создание сервера WebSocket в NodeJS

Чтобы создать сервер WebSocket в NodeJS, вы можете использовать модуль ws , который является наиболее широко используемой реализацией WebSocket для NodeJS.

Во-первых, вам нужно установить wsмодуль в свой проект:

npm install ws
# or
yarn add ws

После того, как вы установили модуль, вы можете сразу же создать index.jsфайл, в котором вы создаете новый сервер WebSocket.

Сначала импортируйте wsмодуль и откройте соединение с сервером WebSocket на определенном порту. Я собираюсь использовать порт 8080 в примере ниже:

const WebSocket = require("ws");

const wss = new WebSocket.Server({ port: 8080 });

Затем напишите код, позволяющий вашему серверу Websocket отправлять сообщение клиенту, когда соединение установлено.

Вам нужно прослушать connectionсобытие WebSocket и send()сообщение при установлении соединения:

wss.on("connection", (ws) => {
  // A connection has been made
  // send back a message
  ws.send("Hi client! You are now connected to me!");
});

Наконец, вам также необходимо прослушать messageсобытие, которое будет запускаться всякий раз, когда клиент отправляет сообщение на сервер следующим образом:

wss.on("connection", (ws) => {
  // A connection has been made
  // send back a message
  ws.send("Hi client! You are now connected to me!");

  // listen to the message event
  // then log the received message
  ws.on("message", (message) => {
    console.log("New message from client: %s", message);
  });
});

И это все, что вам нужно для создания сервера WebSocket с помощью NodeJS. Давайте создадим клиент WebSocket для подключения к вашему wsсерверу из браузера.

Подключение к WebSocket из браузера.

Большинство популярных веб-браузеров, таких как Chrome, Safari и Firefox, уже реализуют собственный JavaScript WebSocket API, который можно использовать для подключения к серверу WebSocket.

Давайте попробуем подключиться к серверу WebSocket с помощью простого HTML-файла.

Сначала создайте index.htmlфайл со следующим <body>содержимым:

<body>
  <h1>WebSocket Client Implementation</h1>
  <button id="wsConnect">Connect to WebSocket</button>
</body>

Затем добавьте прослушиватель событий к <button>элементу, который будет прослушивать clickсобытие.

Слушатель событий выполнит функцию, которая открывает соединение с вашим сервером WebSocket:

const button = document.querySelector("#wsConnect");
button.addEventListener("click", () => {
  const url = "ws://localhost:8080";
  const wsClient = new WebSocket(url);
});

Конструктор new WebSocket()вернет новый объект WebSocket, из которого вы можете прослушивать события, связанные с WebSocket.

Например, вы можете прослушивать WebSocket.onopenсвойство, которое представляет собой обработчик событий, который срабатывает, когда соединение готово для отправки и получения данных:

const button = document.querySelector("#wsConnect");
button.addEventListener("click", () => {
  const url = "ws://localhost:8080";
  const wsClient = new WebSocket(url);

  wsClient.onopen = () => {
    console.log(`Connection to ${url} has been established`);
  };
});

Затем вы также можете прослушать onmessageобработчик событий, который срабатывает, когда клиент получает сообщение:

wsClient.onmessage = (e) => {
  console.log(e.data);
};

Наконец, вы также можете добавить слушателя для onerrorсвойства. Он вызывается, когда соединение WebSocket обнаруживает ошибку:

wsClient.onerror = (err) => {
  console.log(`WebSocket error: ${err}`);
};

Вот полный код HTML-страницы для тестирования соединений WebSocket:

<body>
  <h1>WebSocket Client Implementation</h1>
  <button id="wsConnect">Connect to WebSocket</button>
  <script>
    const button = document.querySelector("#wsConnect");
    button.addEventListener("click", () => {
      const url = "ws://localhost:8080";
      const wsClient = new WebSocket(url);

      wsClient.onopen = () => {
        console.log(`Connection to ${url} has been established`);
      };

      // receive message from the server
      wsClient.onmessage = (e) => {
        console.log(e.data);
      };

      // Log WebSocket error events
      wsClient.onerror = (err) => {
        console.log(`WebSocket error: ${err}`);
      };
    });
  </script>
</body>

Полный список свойств объекта WebSocket можно посмотреть в документации MDN WebSocket .

Пришло время протестировать вашу реализацию WebSocket. Откройте index.htmlфайл в браузере и нажмите на кнопку.

Вы увидите журналы из консоли браузера следующим образом:

Вывод клиента браузера WebSocket

Вывод клиента браузера WebSocket

Вы успешно установили соединение WebSocket между сервером NodeJS и браузером! Попробуйте отправить сообщение на сервер из onopenфункции-обработчика:

wsClient.onopen = () => {
  console.log(`Connection to ${url} has been established`);
  wsClient.send("Hello World!");
};

Вы увидите текст, записанный в консоли NodeJS:

Вывод сервера WebSocket NodeJS

Вывод сервера WebSocket NodeJS

Вы только что узнали, как реализовать соединения WebSocket с помощью NodeJS и браузера. Отличная работа! 😉

В качестве упражнения попробуйте добавить форму с текстовым <input>элементом и кнопкой отправки. Вы можете отправлять сообщение на сервер с помощью WebSocket.send()метода каждый раз, когда нажимается кнопка отправки.

Ссылка: https://sebhastian.com/node-websocket/

#websocket #node #nodejs

Как реализовать соединение WebSocket с помощью NodeJS
高橋  陽子

高橋 陽子

1659435661

如何使用 NodeJS 實現 WebSocket 連接

WebSocket是一種計算機通信協議,它為您提供客戶端和服務器之間的雙向通信通道。

它與瀏覽器中用作標准通信協議的 HTTP 協議有很大不同。

使用 WebSocket 連接,服務器無需等待客戶端請求即可向客戶端發送消息。在 HTTP 連接中,請求必須由客戶端發起。

一旦客戶端和服務器之間建立了 WebSocket 連接,WebSocket 通道將在後台保持打開狀態,因此與 HTTP 連接相比,通信的開銷和延遲更低。

就像你可以創建一個 HTTP 服務器來接收 HTTP 請求一樣,你也可以創建一個 WebSocket 服務器來使用 NodeJS 建立 WebSocket 連接。

本教程將幫助學習如何使用 NodeJS 創建自己的 WebSocket 服務器

完整的實現代碼可以在這個node-websocket-example repo中找到。

在 NodeJS 中創建 WebSocket 服務器

要在 NodeJS 中創建 WebSocket 服務器,可以使用ws 模塊,它是 NodeJS 中使用最廣泛的 WebSocket 實現。

首先,您需要將ws模塊安裝到您的項目中:

npm install ws
# or
yarn add ws

安裝模塊後,您可以立即創建一個index.js文件,在其中創建一個新的 WebSocket 服務器。

首先,導入ws模塊並在特定端口上打開 WebSocket 服務器連接。我將在下面的示例中使用端口 8080:

const WebSocket = require("ws");

const wss = new WebSocket.Server({ port: 8080 });

接下來,編寫代碼讓您的 Websocket 服務器在建立連接時向客戶端發送消息。

建立連接後,您需要監聽 WebSocketconnection事件和send()消息:

wss.on("connection", (ws) => {
  // A connection has been made
  // send back a message
  ws.send("Hi client! You are now connected to me!");
});

最後,您還需要監聽message事件,每當客戶端向服務器發送消息時都會觸發該事件,如下所示:

wss.on("connection", (ws) => {
  // A connection has been made
  // send back a message
  ws.send("Hi client! You are now connected to me!");

  // listen to the message event
  // then log the received message
  ws.on("message", (message) => {
    console.log("New message from client: %s", message);
  });
});

這就是使用 NodeJS 創建 WebSocket 服務器所需的全部內容。ws讓我們創建一個 WebSocket 客戶端以從瀏覽器連接到您的服務器。

從瀏覽器連接到 WebSocket。

Chrome、Safari 和 Firefox 等最流行的 Web 瀏覽器已經實現了原生 JavaScript WebSocket API,您可以使用它來連接到 WebSocket 服務器。

讓我們嘗試使用一個簡單的 HTML 文件連接到 WebSocket 服務器。

首先,創建一個index.html包含以下<body>內容的文件:

<body>
  <h1>WebSocket Client Implementation</h1>
  <button id="wsConnect">Connect to WebSocket</button>
</body>

接下來,將事件偵聽器添加到<button>將偵聽事件的元素click

事件偵聽器將執行一個打開與 WebSocket 服務器連接的函數:

const button = document.querySelector("#wsConnect");
button.addEventListener("click", () => {
  const url = "ws://localhost:8080";
  const wsClient = new WebSocket(url);
});

構造函數new WebSocket()將返回一個新的 WebSocket 對象,您可以從中偵聽 WebSocket 相關事件。

例如,您可以監聽WebSocket.onopen屬性,它是一個在連接準備好發送和接收數據時觸發的事件處理程序:

const button = document.querySelector("#wsConnect");
button.addEventListener("click", () => {
  const url = "ws://localhost:8080";
  const wsClient = new WebSocket(url);

  wsClient.onopen = () => {
    console.log(`Connection to ${url} has been established`);
  };
});

接下來,您還可以偵聽onmessage事件處理程序,該處理程序在客戶端收到消息時觸發:

wsClient.onmessage = (e) => {
  console.log(e.data);
};

最後,您也可以為該onerror屬性添加一個偵聽器。當 WebSocket 連接遇到錯誤時調用它:

wsClient.onerror = (err) => {
  console.log(`WebSocket error: ${err}`);
};

這是用於測試 WebSocket 連接的完整 HTML 頁面代碼:

<body>
  <h1>WebSocket Client Implementation</h1>
  <button id="wsConnect">Connect to WebSocket</button>
  <script>
    const button = document.querySelector("#wsConnect");
    button.addEventListener("click", () => {
      const url = "ws://localhost:8080";
      const wsClient = new WebSocket(url);

      wsClient.onopen = () => {
        console.log(`Connection to ${url} has been established`);
      };

      // receive message from the server
      wsClient.onmessage = (e) => {
        console.log(e.data);
      };

      // Log WebSocket error events
      wsClient.onerror = (err) => {
        console.log(`WebSocket error: ${err}`);
      };
    });
  </script>
</body>

有關 WebSocket 對象屬性的完整列表,您可以查看MDN WebSocket 文檔

是時候測試您的 WebSocket 實現了。index.html從瀏覽器打開文件,然後單擊按鈕。

您將看到來自瀏覽器控制台的日誌,如下所示:

WebSocket 瀏覽器客戶端輸出

WebSocket 瀏覽器客戶端輸出

您已經成功地在 NodeJS 服務器和瀏覽器之間建立了 WebSocket 連接!onopen嘗試從處理函數向服務器發送消息:

wsClient.onopen = () => {
  console.log(`Connection to ${url} has been established`);
  wsClient.send("Hello World!");
};

您將看到從 NodeJS 控制台記錄的文本:

WebSocket NodeJS 服務器輸出

WebSocket NodeJS 服務器輸出

您剛剛學習瞭如何使用 NodeJS 和瀏覽器實現 WebSocket 連接。很好!😉

作為練習,嘗試添加一個帶有文本<input>元素和提交按鈕的表單。WebSocket.send()每次單擊提交按鈕時,您都可以使用方法將消息發送到服務器。

鏈接:https ://sebhastian.com/node-websocket/

#websocket #node #nodejs

如何使用 NodeJS 實現 WebSocket 連接
Hoang  Kim

Hoang Kim

1659424793

Cách Triển Khai Kết Nối WebSocket Bằng NodeJS

WebSocket là một giao thức truyền thông máy tính cung cấp cho bạn một kênh giao tiếp hai chiều giữa máy khách và máy chủ.

Nó hoàn toàn khác với giao thức HTTP được sử dụng làm giao thức truyền thông tiêu chuẩn trong trình duyệt.

Với kết nối WebSocket, máy chủ có thể gửi tin nhắn đến máy khách mà không cần đợi yêu cầu của máy khách. Trong kết nối HTTP, một yêu cầu phải được khởi tạo bởi máy khách.

Khi kết nối WebSocket đã được thiết lập giữa máy khách và máy chủ, kênh WebSocket sẽ được giữ ở chế độ nền để giao tiếp có chi phí thấp hơn và độ trễ khi so sánh với kết nối HTTP.

Cũng giống như cách bạn có thể tạo máy chủ HTTP để nhận các yêu cầu HTTP, bạn cũng có thể tạo máy chủ WebSocket để thiết lập kết nối WebSocket bằng NodeJS.

Hướng dẫn này sẽ giúp tìm hiểu cách tạo máy chủ WebSocket của riêng bạn với NodeJS

Mã triển khai đầy đủ có thể được tìm thấy trong repo nút-websocket-ví dụ này .

Tạo máy chủ WebSocket trong NodeJS

Để tạo một máy chủ WebSocket trong NodeJS, bạn có thể sử dụng mô-đun ws , đây là phần triển khai WebSocket được sử dụng rộng rãi nhất cho NodeJS.

Trước tiên, bạn cần cài đặt wsmô-đun vào dự án của mình:

npm install ws
# or
yarn add ws

Khi bạn đã cài đặt mô-đun, bạn có thể tạo ngay một index.jstệp nơi bạn tạo một máy chủ WebSocket mới.

Đầu tiên, nhập wsmô-đun và mở kết nối máy chủ WebSocket trên một cổng cụ thể. Tôi sẽ sử dụng cổng 8080 trong ví dụ dưới đây:

const WebSocket = require("ws");

const wss = new WebSocket.Server({ port: 8080 });

Tiếp theo, viết mã để cho phép máy chủ Websocket của bạn gửi tin nhắn đến máy khách khi kết nối đã được thiết lập.

Bạn cần nghe connectionsự kiện WebSocket và send()thông báo khi kết nối đã được thực hiện:

wss.on("connection", (ws) => {
  // A connection has been made
  // send back a message
  ws.send("Hi client! You are now connected to me!");
});

Cuối cùng, bạn cũng cần lắng nghe messagesự kiện, sự kiện này sẽ được kích hoạt bất cứ khi nào máy khách gửi thông báo đến máy chủ như sau:

wss.on("connection", (ws) => {
  // A connection has been made
  // send back a message
  ws.send("Hi client! You are now connected to me!");

  // listen to the message event
  // then log the received message
  ws.on("message", (message) => {
    console.log("New message from client: %s", message);
  });
});

Và đó là tất cả những gì bạn cần để tạo một máy chủ WebSocket bằng NodeJS. Hãy tạo một ứng dụng khách WebSocket để kết nối với wsmáy chủ của bạn từ trình duyệt.

Kết nối với WebSocket từ trình duyệt.

Hầu hết các trình duyệt web phổ biến như Chrome, Safari và Firefox đều đã triển khai API WebSocket JavaScript gốc mà bạn có thể sử dụng để kết nối với máy chủ WebSocket.

Hãy thử kết nối với máy chủ WebSocket bằng một tệp HTML đơn giản.

Đầu tiên, hãy tạo một index.htmltệp với <body>nội dung sau:

<body>
  <h1>WebSocket Client Implementation</h1>
  <button id="wsConnect">Connect to WebSocket</button>
</body>

Tiếp theo, thêm trình nghe sự kiện vào <button>phần tử sẽ lắng nghe clicksự kiện.

Trình xử lý sự kiện sẽ thực thi một chức năng mở kết nối đến máy chủ WebSocket của bạn:

const button = document.querySelector("#wsConnect");
button.addEventListener("click", () => {
  const url = "ws://localhost:8080";
  const wsClient = new WebSocket(url);
});

Hàm tạo new WebSocket()sẽ trả về một đối tượng WebSocket mới mà từ đó bạn có thể lắng nghe các sự kiện liên quan đến WebSocket.

Ví dụ: bạn có thể nghe WebSocket.onopenthuộc tính, là một trình xử lý sự kiện được kích hoạt khi kết nối sẵn sàng gửi và nhận dữ liệu:

const button = document.querySelector("#wsConnect");
button.addEventListener("click", () => {
  const url = "ws://localhost:8080";
  const wsClient = new WebSocket(url);

  wsClient.onopen = () => {
    console.log(`Connection to ${url} has been established`);
  };
});

Tiếp theo, bạn cũng có thể nghe onmessagetrình xử lý sự kiện, trình xử lý sự kiện này được kích hoạt khi khách hàng nhận được thông báo:

wsClient.onmessage = (e) => {
  console.log(e.data);
};

Cuối cùng, bạn cũng có thể thêm trình lắng nghe cho thuộc onerrortính. Nó được gọi khi kết nối WebSocket gặp lỗi:

wsClient.onerror = (err) => {
  console.log(`WebSocket error: ${err}`);
};

Đây là mã trang HTML đầy đủ để kiểm tra kết nối WebSocket:

<body>
  <h1>WebSocket Client Implementation</h1>
  <button id="wsConnect">Connect to WebSocket</button>
  <script>
    const button = document.querySelector("#wsConnect");
    button.addEventListener("click", () => {
      const url = "ws://localhost:8080";
      const wsClient = new WebSocket(url);

      wsClient.onopen = () => {
        console.log(`Connection to ${url} has been established`);
      };

      // receive message from the server
      wsClient.onmessage = (e) => {
        console.log(e.data);
      };

      // Log WebSocket error events
      wsClient.onerror = (err) => {
        console.log(`WebSocket error: ${err}`);
      };
    });
  </script>
</body>

Để có danh sách đầy đủ các thuộc tính đối tượng WebSocket, bạn có thể xem tài liệu MDN WebSocket .

Đã đến lúc kiểm tra việc triển khai WebSocket của bạn. Mở index.htmltệp từ trình duyệt của bạn và nhấp vào nút.

Bạn sẽ thấy nhật ký từ bảng điều khiển trình duyệt như sau:

Đầu ra ứng dụng khách trình duyệt WebSocket

Đầu ra ứng dụng khách trình duyệt WebSocket

Bạn đã thiết lập thành công kết nối WebSocket giữa máy chủ NodeJS và trình duyệt! Thử gửi tin nhắn đến máy chủ từ onopenhàm xử lý:

wsClient.onopen = () => {
  console.log(`Connection to ${url} has been established`);
  wsClient.send("Hello World!");
};

Bạn sẽ thấy văn bản được ghi từ bảng điều khiển NodeJS:

Đầu ra máy chủ WebSocket NodeJS

Đầu ra máy chủ WebSocket NodeJS

Bạn vừa học cách triển khai các kết nối WebSocket bằng NodeJS và trình duyệt. Bạn đã làm rất tốt! 😉

Đối với bài tập, hãy thử thêm biểu mẫu có <input>phần tử văn bản và nút gửi. Bạn có thể gửi tin nhắn đến máy chủ bằng cách sử dụng WebSocket.send()phương pháp mỗi khi bấm vào nút gửi.

Liên kết: https://sebhastian.com/node-websocket/

#websocket #node #nodejs

Cách Triển Khai Kết Nối WebSocket Bằng NodeJS
顾 静

顾 静

1658993580

如何在子域上设置 Laravel WebSockets

WebSockets 是许多现代 Web 应用程序的重要组成部分。使用 WebSockets,您可以创建实时更新的应用程序,而无需重新加载页面或不断轮询服务器以进行更改。

Laravel 支持两个开箱即用的服务器端广播驱动程序:Pusher 和 Ably。虽然这两种解决方案可能更容易设置并且可以提供额外的功能,但它们都是商业解决方案。如果您的预算紧张,或者您只是在寻找开源解决方案,这会使它们变得不理想。

Laravel WebSockets 是一个很好的开源替代品。它允许您轻松地将 WebSocket 支持添加到您的 Laravel >5.7 应用程序。它带有调试仪表板和实时统计信息,以及其他功能。

在本教程中,我们将讨论如何在子域上设置 Laravel WebSockets。 

Laravel WebSockets 和 Pusher 的关系

在我们开始学习如何在子域上设置和使用 Laravel WebSockets 之前,让我们回顾一下有关 Laravel WebSockets 和 Pusher 之间关系的一些背景信息,以防止混淆。

当使用Laravel WebSockets时,你应该将 Laravel 的BROADCAST_DRIVER配置设置为pusher. 您还应该设置其他pusher配置,如PUSHER_APP_IDPUSHER_APP_KEYPUSHER_APP_SECRET,以及安装pusher/pusher-php-servercomposer 包。

这使得该软件包看起来像一个需要 Pusher 凭据才能工作的 Pusher 软件开发工具包 (SDK)。但这种情况并非如此。你实际上不需要 Pusher 凭据来使用 Laravel WebSockets!

Laravel WebSockets 背后的主要思想是在不让 Laravel 框架知道这个替换的情况下替换 Pusher 驱动程序。

当你使用 Laravel WebSockets 时,Laravel 认为你使用的是 Pusher 驱动程序,并且会启用这些功能。然而,在底层,这些功能已被 Laravel WebSockets 包所取代。

最重要的是,包用对我们自己的服务器的调用替换了对 Pusher 服务器的调用,然后包处理请求。它还实现了 Pusher 消息协议。因此,所有支持 Pusher 的现有包和应用程序也可以使用该包。

项目和领域结构

如果你有一个标准的 Laravel 设置,其中前端和后端都由 Laravel 放在一个根文件夹中,那么设置这个包的麻烦可能会更少。浏览软件包文档应该可以让您立即启动并运行。

如果您的应用程序的前端与后端完全分离,则您必须进行一些不同的设置。这种设置通常需要两个单独的存储库或至少两个单独的文件夹。以awesomeapp-backendawesomeapp-frontend为例。

然后,您需要设置两个子域以指向每个文件夹,如下所示:

  • awesomeapp.test或者app.awesomeapp.test可以指向您的前端文件夹,称为awesomeapp-frontend
  • api.awesome.test可以指向您的后端文件夹,称为awesomeapp-backend

当你有这样的设置时,你最有可能需要处理的一件事是 CORS。

处理 CORS

网页可以自由地加载来自不同来源的图像、样式表、脚本、iframe 和视频。但是,某些跨域请求,例如 AJAX 请求,默认被所有主流 Web 浏览器实施的同源安全限制所禁止。

跨域资源共享 (CORS) 定义了一种方法来指定此限制的例外情况。它是一种机制,浏览器和服务器可以交互以确定允许跨域请求是否安全。

CORS 对我们有何影响?

那么这对我们意味着什么?好吧,尽管拥有相同的域主机,但我们的子域app.awesomeapp.testapi.awesome.test算作不同的来源。

laravel-echo因此,当我们在前端子域中设置时app.awesomeapp.test,库将尝试向后端子域发出 AJAX 请求api.awesomeapp.test。因为它们将被浏览器视为单独的来源,所以请求将失败......

…除非我们启用 CORS。幸运的是,在 Laravel 中启用 CORS 非常简单。

在 Laravel 中启用 CORS

要为我们的 Laravel WebSocket 服务器配置 CORS,请从Laravel 安装文件夹中打开cors.php配置文件。config将 Laravel 的broadcasting/auth路由添加到paths数组中,并将supports_credentials选项设置为true.

在后台,该supports_credentials选项将您的应用程序的[Access-Control-Allow-Credentials]标头设置为以下值true

// config/cors.php
return [
    'paths' => ['api/*', 'sanctum/csrf-cookie', 'broadcasting/auth'],
    // ...
    'supports_credentials' => true,
t];

或者,您可以将Broadcast::routes方法调用放在您的routes/api.php文件中。这为broadcasting/auth路由添加前缀api/,无需将路由添加到paths数组中,因为默认情况下api/*路径(每个带有api前缀的路由)都在数组中。

调用该Broadcast::routes方法时,您应该指定向通道路由发出请求时要使用的中间件。这可能是auth:api或者auth:sanctum如果你正在使用 Laravel Sanctum。

// routes/api.php
Broadcast::routes(['middleware' => ['auth:sanctum']]);// config/cors.php
return [
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    // ...
    'supports_credentials' => true,
];

此外,请确保来自前端的 HTTP/AJAX 请求已将XMLHttpRequest.withCredentials选项设置为true. 如果您正在使用axios,这可以通过withCredentials在应用程序的全局axios实例上设置选项来完成,如下面的代码所示:

axios.defaults.withCredentials = true;

最后,您应该确保您的应用程序的会话 cookie 可以从您的根域的任何子域访问。这可以通过在.应用程序的config/session.php配置文件中为域添加前缀来完成。

'domain' => '.example.com',

要使配置环境竞争,您应该使用文件中的SESSION_DOMAIN环境变量设置此选项.env

// config/session.php
'domain' => env('SESSION_DOMAIN', null),# .env
# ...
SESSION_DOMAIN=.example.com

现在,让我们继续设置 Laravel WebSockets!

安装laravel-websockets

Laravel WebSockets 可以使用 composer 安装。

composer require beyondcode/laravel-websockets

该软件包附带一个迁移以存储有关您的 WebSocket 服务器的统计信息。如果您不打算使用此功能,则可以跳过此步骤。

运行以下命令发布迁移文件:

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="migrations"

然后,运行迁移:

php artisan migrate

接下来,通过运行以下命令发布 Laravel WebSocket 配置文件:

php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider" --tag="config"

正如我们所讨论的,Laravel WebSockets 包与 Pusher 结合使用,因此我们还需要安装官方 Pusher PHP SDK:

composer require pusher/pusher-php-server "~3.0"

确保使用 Pusher 作为您的广播驱动程序。这可以通过BROADCAST_DRIVER在文件中设置环境变量来完成.env

BROADCAST_DRIVER=pusher

最后,确保在您的文件中设置了APP_NAMEPUSHER_APP_IDPUSHER_APP_KEYPUSHER_APP_SECRET环境变量。.env

注意,您设置的变量无关紧要PUSHER_,只需确保它们对于每个项目都是唯一的。

PUSHER_APP_ID=pusherid
PUSHER_APP_KEY=pusherkey
PUSHER_APP_SECRET=pushersecret
PUSHER_APP_CLUSTER=pushercluster

Laravel WebSockets 配置

如前所述,当从你的 Laravel 应用程序广播事件时,Pusher 驱动程序的默认行为是将事件信息发送到官方的 Pusher 服务器。但是由于 Laravel WebSockets 包自带了自己的 Pusher API 实现,我们需要告诉 Laravel 将事件信息发送到我们自己的服务器。

我们通过将hostandport配置键添加到文件的pusher部分来做到这一点config/broadcasting.php。Laravel WebSocket 服务器的默认端口是6001.

'pusher' => [
    'driver' => 'pusher',
    'key' => env('PUSHER_APP_KEY'),
    'secret' => env('PUSHER_APP_SECRET'),
    'app_id' => env('PUSHER_APP_ID'),
    'options' => [
        'cluster' => env('PUSHER_APP_CLUSTER'),
        'encrypted' => true,
        'host' => '127.0.0.1',
        'port' => 6001,
        'scheme' => 'http'
    ],
],

配置 WebSocket 应用程序

Laravel WebSockets 使用开箱即用apps支持多租户的概念。这允许您将包与当前的 Laravel 应用程序分开托管,并使用一台服务器为多个 WebSocket 应用程序提供服务。

默认应用使用您现有的 Pusher 配置。这应该适用于大多数用例。

'apps' => [
    [
        'id' => env('PUSHER_APP_ID'),
        'name' => env('APP_NAME'),
        'key' => env('PUSHER_APP_KEY'),
        'secret' => env('PUSHER_APP_SECRET'),
        'enable_client_messages' => false,
        'enable_statistics' => true,
    ],
],

确保在广播配置部分中使用相同id的 、keysecret,否则从 Laravel 广播事件将不起作用。

客户消息

通常,所有 WebSocket 消息在广播给其他用户之前都会通过你的 Laravel 应用程序。但有时您可能希望将事件直接从一个客户端发送到另一个客户端,而不需要发送到服务器。

例如,在聊天应用程序中进行打字事件。您可以使用密钥为config/websockets.php配置文件中的每个应用程序配置此选项。enable_client_messages

您应该谨慎使用此功能,因为这些事件消息来自其他用户并且可能会被篡改。

统计数据

如前所述,Laravel WebSockets 包附带了一个仪表板来监视有关 WebSocket 服务器的统计信息。要为您的任何应用启用或禁用此功能,您可以修改该enable_statistics选项。

在 Laravel 中启用事件广播

要在 Laravel 中启用事件广播,您需要注册App\Providers\BroadcastServiceProvider. 您可以通过添加App\Providers\BroadcastServiceProvider::class到文件的providers数组来做到这一点config/app.php

'providers' => [
   // ...
    App\Providers\BroadcastServiceProvider::class,
    // ...
],

在新的 Laravel 应用程序中,此提供程序已经在数组中,您只需取消注释即可。包含注册广播授权路由和回调所需的代码
BroadcastServiceProvider

如果您之前Broadcast::routes在文件中添加了该方法routes/api.php,您可以安全地bootBroadcastServiceProvider.

public function boot()
{
    // Broadcast::routes();
    require base_path('routes/channels.php');
}

这就是后端的全部内容,现在让我们设置前端应用程序!

设置 Laravel Echo

Laravel Echo是一个 JavaScript 库,它使订阅频道和监听 Laravel 服务器端广播驱动程序广播的事件变得非常容易。在这种情况下,它是 Laravel Websockets 的 Pusher API 实现。

Echo 可以通过 npm 包管理器轻松安装。pusher-js由于 Laravel Websockets 包使用 Pusher Channels 广播器,我们还将安装:

npm install --save-dev laravel-echo pusher-js

为了让 Laravel Echo与 Laravel WebSockets 一起工作,我们在初始化 Laravel Echo 时需要注意一些配置选项。具体来说,我们需要添加wsHostwsPort参数并将它们指向我们的 Laravel WebSocket 服务器主机和端口。

为了让 Laravel WebSocket 授权请求成功,我们还需要提供一个自定义的身份验证端点 usingauthEndpoint和一个使用auth.headers.Authorization.

authEndpoint省略该选项时,Laravel Echo 将尝试使用运行它的同一主机进行身份验证。但在我们的例子中,由于 WebSocket 服务器位于不同的子域上,请求将失败。

注意,如果您的Broadcast::routes方法调用在App\Providers\BroadcastServiceProvider文件中,这是默认设置,您的值authEndpoint应该类似于:http://api.awesomeapp.test/broadcasting/auth.

如果您将方法调用放在routes/api.php文件中,那么它应该类似于:http://api.awesomeapp.test/api/broadcasting/auth.

import Echo from "laravel-echo"
window.Pusher = require('pusher-js');

window.Echo = new Echo({
  broadcaster: 'pusher',
  key: 'pusherkey',
  wsHost: 'api.websockets.test',
  wsPort: 6001,
  // wssPort: 6001,
  forceTLS: false,
  // encrypted: true,
  disableStats: true,
  auth: { headers: { Authorization: 'Bearer sometoken' } },
  authEndpoint: 'http://api.awesomeapp.test/api/broadcasting/auth', // OR
  // authEndpoint: 'http://api.awesomeapp.test/broadcasting/auth',
})

或者,您可以在初始化 Laravel Echo 时配置自定义授权方。这允许您配置 Laravel Echo 以使用您的全局axios实例,该实例应该为跨域请求正确配置并使用正确的授权标头。

import Echo from "laravel-echo"
window.Pusher = require('pusher-js');

window.Echo = new Echo({
  broadcaster: 'pusher',
  key: 'pusherkey',
  wsHost: 'api.awesomeapp.test',
  wsPort: 6001,
  // wssPort: 6001, // For SSL
  forceTLS: false,
  // encrypted: true, // For SSL
  disableStats: true,
  authorizer: (channel, options) => {
    return {
      authorize: (socketId, callback) => {
        axios
          .post('/api/broadcasting/auth', {
            socket_id: socketId,
            channel_name: channel.name,
          })
          .then((response) => {
            callback(false, response.data)
          })
          .catch((error) => {
            callback(true, error)
          })
      },
    }
  },
})

确保 的值与后端配置中的值key相同。PUSHER_APP_KEY

默认情况下,Pusher JavaScript 客户端会尝试发送统计信息,但我们可以使用该disableStats选项禁用此功能。

将 Laravel WebSockets 与自定义 SSL 证书结合使用时,请务必使用该wssPort选项而不是wsPort. 此外,使用该encrypted选项并将其设置为true.

就是这样!现在您可以将 Laravel Echo 功能与 Laravel WebSockets 结合使用。

结论

在本文中,我们了解了有关 Laravel WebSockets 的所有信息。我们讨论了包和 Pusher 之间的关系,在处理多个子域时如何处理 CORS,以及如何在我们的应用程序中设置 Laravel WebSockets。我们还学习了如何设置 Laravel Echo 以使用 Laravel WebSockets,尤其是在使用多个子域时。

虽然该laravel-websockets包的主要目的是使 Pusher JavaScript 客户端或 Laravel Echo 尽可能易于使用,但您不仅限于此用例或 Pusher 协议。

要了解有关如何在其他用例中使用该包的更多信息,请查看Laravel WebSockets 文档

来源:https ://blog.logrocket.com/how-to-set-up-laravel-websockets-subdomain/

#websocket #laravel 

如何在子域上设置 Laravel WebSockets