我用express创建了一个简单的nodejs服务器来监听websocket连接,接收" ping"字符串并返回" pong"回到客户端。
除了客户端没有收到" pong"从服务器,即使服务器据称发送它。不确定问题是在客户端还是服务器端。我也在localhost上运行它,但这不应该是一个问题。
服务器
var express = require('express');
var WebSocketServer = require('ws').Server;
var app = express();
var wsServer = app.listen(3000, function() {
var host = wsServer.address().address;
var port = wsServer.address().port;
console.log('App listening at ws://%s:%s', host, port);
});
var wss = new WebSocketServer({server: wsServer});
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('Got: %s', message);
ws.send('Pong');
console.log('Sent Pong');
});
ws.on('close', function() {
console.log('Closed Connection');
});
});
module.exports = server;
客户端
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
if ("WebSocket" in window) {
console.log("WebSocket is supported by your Browser!");
}
else {
console.log("WebSocket NOT supported by your Browser!");
};
</script>
<script type="text/javascript">
function WebSocketTest() {
var ws = new WebSocket("ws://localhost:3000");
ws.onopen = function() {
var msg = {
msg: 'ping'
};
ws.send('Ping');
console.log('Message sent to server');
};
ws.onmessage = function(evt) {
var received_msg = evt.data;
console.log('Message received from server: ' + received_msg);
};
ws.onclose = function() {
console.log('Connection closed');
};
};
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>