ksh*_*har 21 javascript websocket node.js npm
仅关注客户端 API(因为每个服务器端语言都有自己的 API),以下代码段打开一个连接,为连接、断开连接和消息事件创建事件侦听器,将消息发送回服务器,然后关闭使用 WebSocket 连接。
// Create a socket instance
var socket = new WebSocket('ws://localhost:3000');
// Open the socket
socket.onopen = function(event) {
// Send an initial message
socket.send('I am the client and I\'m listening!');
// Listen for messages
socket.onmessage = function(event) {
console.log('Client received a message',event);
};
// Listen for socket closes
socket.onclose = function(event) {
console.log('Client notified socket has closed',event);
};
// To close the socket....
socket.close()
};
Run Code Online (Sandbox Code Playgroud)
但是我在执行上面的代码片段时遇到错误:
参考错误:未定义 WebSocket
我已经浏览了各种链接,如https://davidwalsh.name/websocket,关于如何实现 WebSockets。但是他们都没有导入任何npm package。
问题:那么,如何实现 WebSockets(客户端 AngularJS)?我在这里缺少什么?
小智 23
尝试
const WebSocket = require('ws');
var socket = new WebSocket('ws://localhost:3000');
Run Code Online (Sandbox Code Playgroud)
然后
npm 我是
并重试。它适用于我的情况
Vla*_*ego 17
我将其留在这里是为了那些@stomp/stompjs在节点应用程序中遇到问题的人。
添加这一行:
Object.assign(global, { WebSocket: require('ws') });
另外,别忘了npm install ws
| 归档时间: |
|
| 查看次数: |
32632 次 |
| 最近记录: |