字节笔记本字节笔记本

WebSocket 传输文本(字符串)和二进制数据 代码示范

2024-02-25

示例代码展示了使用WebSocket在客户端和服务器端之间传输文本和二进制数据的方法。

  1. 传输文本(字符串)数据代码示例:
// 客户端代码
const webSocket = new WebSocket('ws://localhost:3000');

webSocket.onopen = () => {
  const message = 'Hello, WebSocket!';
  webSocket.send(message);
};

webSocket.onmessage = (event) => {
  console.log('Received message:', event.data);
};

// 服务器端代码(使用 Node.js 的 ws 模块)
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    console.log('Received message:', message);
    ws.send('Message received: ' + message);
  });
});
  1. 传输二进制数据代码示例:
// 客户端代码
const webSocket = new WebSocket('ws://localhost:3000');

webSocket.binaryType = 'arraybuffer';

webSocket.onopen = () => {
  const buffer = new ArrayBuffer(8);
  const view = new Uint8Array(buffer);
  for (let i = 0; i < view.length; i++) {
    view[i] = i;
  }
  webSocket.send(buffer);
};

webSocket.onmessage = (event) => {
  console.log('Received binary data:', new Uint8Array(event.data));
};

// 服务器端代码
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3000 });

wss.on('connection', (ws) => {
  ws.on('message', (data) => {
    const binaryData = new Uint8Array(data);
    console.log('Received binary data:', binaryData);
  });
});

以上示例演示了如何使用 WebSocket 传输文本数据和二进制数据。在客户端和服务器端均使用 WebSocket 建立连接,并分别发送和接收消息或数据。在客户端通过 webSocket.send 发送消息或数据,在服务器端通过 ws.on('message') 接收消息或数据。