websocket事件
websocket可以监听的事件 服务端的事件connection、message、close等。。。。 客户端的事件open、message、close、error等四个事件
ws模块创建websocket
server.js
const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server;
const ws = new WebSocketServer({port:8080});
ws.on("connection", function (socket) {
socket.on('message', function (msg) {
socket.send(msg);
console.log(msg);
})
})
client.js
const WebSocket = require('ws')
const ws = new WebSocket('ws://192.168.1.202:8080')
ws.on('open', () => {
ws.send('Hello')
})
ws.on('message', (message) => {
console.log(message)
})
网页端监听 webAPI
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>socket</title>
</head>
<body>
</body>
<script type="text/javascript" src="/static/js/jquery.min.js"></script>
<script type="text/javascript">
(function(){
let ws = new WebSocket('ws://192.168.1.202:8080');
ws.addEventListener('open',function(e){
ws.send("Hello WebSockets!");
})
ws.addEventListener('message',function(e){
console.log(e.data);
})
})(window);
</script>
</html>
express和ws模块联动
只需要监听http服务就可以,不用监听app,express详细信息额外配置
const express = require('express');
const app = express();
var WebSocket = require('ws');
var http = require('http');
var server = http.createServer(app)
var ws = new WebSocket.Server({ server})
ws.on("connection", function (socket) {
socket.on('message', function (msg) {
socket.send(msg);
console.log(msg);
})
})
const port = 8080;
server.listen(port);
|