欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

原生nodejs使用websocket代码分享

程序员文章站 2024-02-07 10:33:52
安装: npm  install  ws 服务端(nodejs): var websocketserver = require...

安装:

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>