簡體   English   中英

Javascript Websocket-如何使發送數據像在socket.io中一樣?

[英]Javascript websocket - how to make sending data like in socket.io?

就像標題所說,有沒有辦法像在socket.io中那樣在websocket中發送數據?

我正在將uWS與nodejs用作服務器。

我的意思是這樣的:

// client
var ws = new WebSocket('ws://localhost:3000/');

ws.send("event1",{data1:100,data2:500,etc:"so on"});

// server

//receive that message like so
ws.on("event1",function(data){
    console.log(data.data1,data.data2,data.etc)
    ws.send("sendbackThisMessage",data);
});

// client

//receive that message like so
ws.on("sendbackThisMessage",function(data){
    console.log(data.data1,data.data2,data.etc)
});

將socket.io引擎替換為uWS引擎

const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const uws = require('uws');

const app = express();
const server = http.Server(app);
const io = socketIO(server);

io.ws = new uws.Server({ perMessageDeflate: false, noServer: true });

io.on('connection', (socket) => {
  io.emit('data', 'hello!'); 
  // or
  socket.emit('data', 'hello')
});


server.listen(3000, () => console.log('Socket.IO Running...'));

在該版本上進行了測試:

節點:v7.8.0

"dependencies": {
  "express": "^4.15.3",
  "socket.io": "^2.0.3",
  "uws": "^8.14.0"
}

基於udgwebdev的基礎,但是該站點的示例對我不起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM