简体   繁体   English

如何从对象外部调用函数

[英]How to call a function from outside the object

I am trying to make a proxy between sockets and websockets. 我正在尝试在套接字和websocket之间建立代理。 I receive requests on socket server and I want to proxy them to websocket clients, however websocket.ws.send appears to be undefined. 我在套接字服务器上收到请求,我想将它们代理到websocket客户端,但是websocket.ws.send似乎未定义。 What would be the correct way of doing this? 正确的做法是什么? How to call ws.send() from outside of the object? 如何从对象外部调用ws.send()?

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 8001}),
var net = require('net')


websocket = wss.on('connection', function(ws) {
    ws.on('message', function(message) {
        console.log('received: %s', message);
    });
    ws.send("NEW USER JOINED");
});


var socketServer = net.createServer(function(socket) {
        socket.on("data", function(data){
                console.log("Received: "+data)
                websocket.ws.send("Message")
        });
});
socketServer.listen(1337, '127.0.0.1');

The problem you have is that ws is a single web socket for one connection. 您的问题是ws是一个连接的单个Web套接字。 It is not a property on the websocket object, but an argument to a callback you define. 它不是websocket对象的属性,而是您定义的回调的参数。 Each time someone connects you will get a connection event which will execute your callback, allowing you to bind a function to that specific web socket for the message event. 每次有人连接时,您都会获得一个connection事件,该事件将执行您的回调,使您可以将函数绑定到message事件的特定Web套接字。

You either need to store the ws object in a variable that the socket server can access or you could broadcast to all clients. 您需要将ws对象存储在套接字服务器可以访问的变量中,或者可以广播给所有客户端。

wss.clients.forEach(function each(client) {
   client.send(data);
});

This will work fine if you only have one client, however if you have multiple connections to both the websocket and socket server then you need to use a method of identifying connections on both so that you can locate the websocket connection you need to send data to. 如果您只有一个客户端,这将很好地工作,但是,如果您同时连接到websocket和套接字服务器,则需要使用一种在两者上都标识连接的方法,以便可以找到需要向其发送数据的websocket连接。 。

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

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