前端javascript如何运用WebSocket

2024年06月12日 建站教程

WebSocket是单个TCP连接上的全双工通信协议,它允许服务器主动向客户端推送信息,而无需客户端轮询。下面web建站小编给大家简单介绍一下!

具体代码如下:

//前端代码
let socket = new WebSocket('ws://localhost:3000');
 
socket.onopen = function(event) {
  socket.send('from client: Hello');
};
 
socket.onmessage = function(event) {
  console.log(event.data);
};
 
socket.onerror = function(event) {
  console.log('WebSocket error: ' + event.data);
};
 
//Node.js代码
let WebSocketServer = require('ws').Server;
let wss = new WebSocketServer({ port: 3000 });
 
wss.on('connection', function(ws) {
  ws.on('message', function(message) {
    console.log('Received from client: %s', message);
    ws.send('from server: Hello');
  });
 
  ws.on('close', function() {
    console.log('WebSocket closed!');
  });
});

本文链接:http://so.lmcjl.com/news/6404/

展开阅读全文
相关内容