简体   繁体   English

如何使这个 websocket 实时?

[英]How to make this websocket real time?

I'm integrating websockets with express on the backend and using browser's native websocket api on the client side.我在后端将 websockets 与 express 集成,并在客户端使用浏览器的原生 websocket api。 I have so far been able to send and receive message from the client to server and server back to client.到目前为止,我已经能够从客户端向服务器发送和接收消息,从服务器向客户端发送和接收消息。 But all this happens with a page refresh only.但是所有这一切都只发生在页面刷新上。 Isn't websocket supposed to be real time? websocket 不应该是实时的吗? Lets say I make a change in the message on server file, then it has to immediately reflect in my browser's console.假设我对服务器文件上的消息进行了更改,然后它必须立即反映在我的浏览器控制台中。 and lets say I make a change in the message in the script file on the client side, then it has to immediately show the changes on server's console.(Also I'm using nodemon to run the server so changes has to reflect pretty quickly).假设我在客户端的脚本文件中更改了消息,然后它必须立即在服务器的控制台上显示更改。(另外我正在使用 nodemon 运行服务器,因此更改必须很快反映出来) . But right now, I see myself making a request to / via page refresh and then server upgrading and then responding back with the message.但是现在,我看到自己通过页面刷新向/发出请求,然后服务器升级,然后回复消息。

Please tell me if I'm missing something in the code or otherwise in the concept?请告诉我我是否在代码或概念中遗漏了什么?

app.js应用程序.js


const express = require('express')
const app = express()
const path = require('path')
const WebSocketServer = require('websocket').server; 


app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, '/public')))

const port = 8080





app.get('/', (req, res) => {
  res.render('index')
})

const server = app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})




wsServer = new WebSocketServer({
    httpServer: server
});

function originIsAllowed(origin) {
  return true;
}


wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }
    
    var connection = request.accept(null, request.origin);
    console.log((new Date()) + ' Connection accepted.');
    
    connection.on('message', function(message) {

        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF("server says hi");
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }

    });

    
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});

client.js:客户端.js:


const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello to Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

I am not sure if I understand the question, but if you want the client to send message to server, you have do it the same way as it is done in open listener:我不确定我是否理解这个问题,但是如果您希望客户端将消息发送到服务器,您可以使用与在开放式侦听器中相同的方式进行操作:
socket.send('MESSAGE FOR SERVER') or, if server should send something to client, then just connection.send('MESSAGE FOR CLIENT') . socket.send('MESSAGE FOR SERVER')或者,如果服务器应该向客户端发送一些东西,那么只需connection.send('MESSAGE FOR CLIENT') Realtime communication with WebSocket means, the connection is created only once and the protocol is kept opened (Unlike REST API, where the connection is created with every request.) The message must be sent actively either from server or client, there is nothing observing some message state and updating it on the other side.与 WebSocket 的实时通信意味着,仅创建一次连接并保持协议保持打开状态(与 REST API 不同,其中连接必须通过观察每个请求来主动创建服务器或没有任何消息发送。)消息 state 并在另一侧更新它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM