本文给大家分享的是在原生的nodejs中如何使用websocket实现信息传输,非常实用,有需要的小伙伴可以参考下
安装:
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>
|