原生nodejs使用websocket代码分享
程序员文章站
2023-12-27 19:15:15
安装:
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>