当前位置:主页 > 脚本语言 > NodeJS >

原生nodejs使用websocket代码分享

时间:2021-03-09 10:07:27 | 栏目:NodeJS | 点击:

安装:

npm  install  ws

服务端(nodejs):

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function (ws) {
console.log('client connected');
ws.on('message', function (message) {
  console.log(message);
});
});


客户端:

<script>
var ws = new WebSocket("ws://localhost:8080");
ws.onopen = function (e) {
  console.log('Connection to server opened');
  sendMessage();
}
function sendMessage() {
  ws.send('hello');
}
</script>

您可能感兴趣的文章:

相关文章