Home > Backend Development > PHP Tutorial > WebSocket application scenarios in web applications

WebSocket application scenarios in web applications

王林
Release: 2023-10-15 10:34:02
Original
1264 people have browsed it

WebSocket application scenarios in web applications

Application scenarios of WebSocket in Web applications

WebSocket is a protocol for two-way communication between modern web browsers and servers. Unlike the traditional HTTP protocol, WebSocket allows the server to actively send data to the client without requiring the client to initiate a request. This real-time two-way communication feature makes WebSocket widely used in a variety of Web application scenarios.

  1. Instant chat application
    Instant chat application is one of the most common application scenarios of WebSocket. When performing real-time communication, the traditional HTTP protocol needs to continuously send requests to the server through long polling or short polling to obtain the latest news. This approach potentially increases the load on the server, and message latency is affected by the frequency of polling. WebSocket can establish a persistent connection, and when the server has new messages, it can be pushed directly to the client to achieve real-time message push. The following is a simple sample code for an instant chat application using WebSocket:
// 客户端代码
const socket = new WebSocket('ws://server:port/chat');

socket.onopen = function() {
  console.log('WebSocket连接已建立');
};

socket.onmessage = function(event) {
  const message = event.data;
  console.log('接收到消息:', message);
  // 处理接收到的消息
};

socket.onclose = function(event) {
  console.log('WebSocket连接已关闭');
};

document.querySelector('#send-button').addEventListener('click', function() {
  const message = document.querySelector('#message-input').value;
  socket.send(message);
});

// 服务器端代码(使用Node.js和ws库)
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function(ws) {
  console.log('已建立WebSocket连接');

  ws.on('message', function(message) {
    console.log('接收到消息:', message);
    // 处理接收到的消息

    // 模拟回复消息
    ws.send('收到消息:' + message);
  });

  ws.on('close', function() {
    console.log('WebSocket连接已关闭');
  });
});
Copy after login
  1. Real-time data display
    In some Web applications that require real-time display of data, such as stock quotes and websites Access statistics, etc., WebSocket can also provide good support. Through the WebSocket connection, the server can push the latest data to the client in real time, and the client can update the display in time according to changes in data. The following is a sample code that uses WebSocket to display stock quotes in real time:
// 客户端代码
const socket = new WebSocket('ws://server:port/stock');

socket.onopen = function() {
  console.log('WebSocket连接已建立');
};

socket.onmessage = function(event) {
  const stockData = JSON.parse(event.data);
  console.log('接收到股票数据:', stockData);
  // 更新展示最新股票行情
};

socket.onclose = function(event) {
  console.log('WebSocket连接已关闭');
};

// 服务器端代码(使用Node.js和ws库)
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function(ws) {
  console.log('已建立WebSocket连接');

  // 模拟每秒推送一次股票数据
  const stockData = {
    symbol: 'AAPL',
    price: 150.25,
    timestamp: Date.now()
  };

  setInterval(function() {
    ws.send(JSON.stringify(stockData));
  }, 1000);

  ws.on('close', function() {
    console.log('WebSocket连接已关闭');
  });
});
Copy after login
  1. Multiple Collaborative Editing
    In collaborative editing applications, multiple users can edit the same document at the same time. The traditional implementation method is that the server is responsible for broadcasting the user's editing operations to other users, and other users make corresponding changes based on the editing operations. Using WebSocket can more conveniently realize the collaborative editing function of multiple people. The following is a simple example code for using WebSocket to implement multi-person collaborative editing:
// 客户端代码
const socket = new WebSocket('ws://server:port/editor');

socket.onopen = function() {
  console.log('WebSocket连接已建立');
};

socket.onmessage = function(event) {
  const editorData = JSON.parse(event.data);
  console.log('接收到编辑数据:', editorData);
  // 更新文档内容
};

socket.onclose = function(event) {
  console.log('WebSocket连接已关闭');
};

// 用户编辑操作示例(假设使用Quill.js作为富文本编辑器)
const editor = new Quill('#editor-container', {
  theme: 'snow'
});

editor.on('text-change', function(delta, oldDelta, source) {
  if (source === 'user') {
    const editorData = {
      delta: delta,
      timestamp: Date.now()
    };
    socket.send(JSON.stringify(editorData));
  }
});

// 服务器端代码(使用Node.js和ws库)
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function(ws) {
  console.log('已建立WebSocket连接');

  ws.on('message', function(message) {
    const editorData = JSON.parse(message);
    console.log('接收到编辑数据:', editorData);
    // 处理编辑操作

    // 广播编辑操作给其他用户
    wss.clients.forEach(function(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify(editorData));
      }
    });
  });

  ws.on('close', function() {
    console.log('WebSocket连接已关闭');
  });
});
Copy after login

Summary:
The emergence of WebSocket has greatly promoted the real-time communication capabilities of Web applications. WebSocket can play a great role in scenarios such as instant chat, real-time data display, and multi-person collaborative editing. Developers can use WebSocket to easily implement these functions and improve user experience and application real-time performance. At the same time, it is worth noting that developers should consider network security and performance issues when using WebSocket to ensure application stability and security.

The above is the detailed content of WebSocket application scenarios in web applications. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template