我正在尝试使用HTML5网络套接字为基于jQuery的前端构建ExpressJS websocket后端。
ExpressJS后端代码实际上是从https://github.com/websockets/ws#expressjs-example
复制粘贴的javascript前端代码为:
var socket = new WebSocket("ws://localhost:8080");
socket.onopen = function(){
console.log( "OPENED : ", socket.readyState );
}
socket.onmessage = function(msg){
console.log( msg );
}
socket.onclose = function(){
console.log( "CLOSED : ", socket.readyState );
}
setTimeout(function(){
socket.send('test');
}, 2000);
在Chrome中,我收到错误:"连接在收到握手响应之前已关闭"。我已经在网上寻找解决方案,但它们都是基于socket.io的,而我只是使用NodeJS ws包。
任何提示都将不胜感激。
答案 0 :(得分:1)
后端代码:
const express = require('express')
const http = require('http')
const WebSocket = require('ws')
var path = require('path')
const app = express()
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/a.html'))
})
const server = http.createServer(app)
const wss = new WebSocket.Server({ server })
wss.on('connection', function connection (ws, req) {
ws.on('message', function incoming (message) {
console.log('received: %s', message)
})
ws.send('something')
})
server.listen(8080, function listening () {
console.log('Listening on %d', server.address().port)
})
唯一的变化是第8行的app.get
,而不是您提供的链接中提供的app.use
。
a.html
文件只有前端脚本:
<html>
<head>
</head>
<body>
<script>
var socket = new WebSocket("ws://localhost:8080");
socket.onopen = function () {
console.log("OPENED : ", socket.readyState);
}
socket.onmessage = function (msg) {
console.log(msg);
}
socket.onclose = function () {
console.log("CLOSED : ", socket.readyState);
}
setTimeout(function () {
socket.send('test');
}, 2000);
</script>
</body>
</html>
一切都很好。
您说您正在端口3000上运行服务器,但您正在尝试连接前端代码中的端口8080。这是一个错误吗?
答案 1 :(得分:0)
使用socket.io禁食且最可靠,实施和配置起来要容易得多。