Wal*_*ari 8 javascript websocket node.js express
我想知道什么是websocket事件到目前为止我只使用了这个ws.on('message')事件,但是我想使用在建立和关闭连接时触发的事件.我尝试添加ws.on('connection'),但没有被触发.
我的代码:
app.ws('/', function (ws, req) {
ws.on('message', function (textChunk) {
//do stuff
}
});
});
Run Code Online (Sandbox Code Playgroud)
我需要一些客户端编程来执行此操作吗?
我尝试添加它,但是当我从客户端连接时它没有触发.
ws.on('request', function () {
console.log("request");
});
Run Code Online (Sandbox Code Playgroud)
提供的功能app.ws是在打开新的websocket时执行的功能.所以以这种方式使用它:
app.ws('/', function (ws, req) {
console.log("New connection has opened!");
ws.on('close', function() {
console.log('The connection was closed!');
});
ws.on('message', function (message) {
console.log('Message received: '+message);
});
});
Run Code Online (Sandbox Code Playgroud)
查看源代码后,express-ws您可以执行以下操作.
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
// get the WebsocketServer instance with getWss()
// https://github.com/HenningM/express-ws/blob/5b5cf93bb378a0e6dbe6ab33313bb442b0c25868/index.js#L72-L74
expressWs.getWss().on('connection', function(ws) {
console.log('connection open');
});
// ... express middleware
// ... websocket middle ware
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
});
app.listen(3000);Run Code Online (Sandbox Code Playgroud)
有以下内容:
close
error
message
open
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Attributes
| 归档时间: |
|
| 查看次数: |
5341 次 |
| 最近记录: |