简体   繁体   English

socket.io-套接字不是仅在客户端上定义

[英]socket.io - socket is not defined on client only

I'm running two instances of socket.io on my local machine (two namespaces). 我正在本地计算机(两个名称空间)上运行socket.io的两个实例。 The present issue is that when trying to connect from the client side (to any namespace), I get the following error: 当前的问题是,当尝试从客户端(连接到任何名称空间)连接时,出现以下错误:

Uncaught ReferenceError: socket is not defined

I tested this without custom namespaces and the same issue arose. 我在没有自定义名称空间的情况下进行了测试,并且出现了相同的问题。 The server side is just fine as I can emit events. 服务器端很好,因为我可以发出事件。

The Client code looks like this: 客户端代码如下所示:

Client 客户

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js"></script>

<script>
var socketOptions           = {};
socketOptions.transports    = ['polling'];
var client                  = new PlayClient();

var playSocket  = io.connect('http://localhost:8044/clients', socketOptions);

playSocket.on('connect', function(socket) {
    console.clear();
    console.info("CLIENT: Connected.");

    socket.on("client:change scene", function(newSceneId) {
        console.log(newSceneId);
        client.changeScene(newSceneId);
    });

});
</script>

It looks like I just overwrote the socket. 看来我只是改写了套接字。 So, basic troubleshooting led me to this answer leading me to confirm that. 因此,基本的故障排除使我得到了这个答案,使我得以确认。 However, passing (data) or something else instead still leaves socket undefined but with the console declaring: TypeError: undefined . 但是,传递(data)或其他方法仍然会导致socket未定义,但控制台会声明: TypeError: undefined

If I change .on('connect') to .on('connection') , the socket is no longer overwritten but fails to connect or receive any emitted events because the socket.io client does not understand the 'connection' event . 如果我将.on('connect')更改为.on('connection') ,则套接字将不再被覆盖,但由于socket.io 客户端无法理解'connection'事件,因此无法连接或接收任何发出的事件

Any help with this is much appreciated, as I seem to be caught in a circular rut. 非常感谢您提供任何帮助,因为我似乎陷入了麻烦。

you seem to be confusing server side and client side events; 您似乎混淆了服务器端和客户端事件; they are pretty different. 他们是完全不同的。 each client object can only be connected to a single server, while the server can receive many connections 每个客户端对象只能连接到单个服务器,而服务器可以接收许多连接

maybe try something like: 也许尝试类似的东西:

var playSocket  = io.connect('http://localhost:8044/clients', socketOptions);

playSocket.on('connect', function() {
    console.clear();
    console.info("CLIENT: Connected.");
}

playSocket.on("client:change scene", function(newSceneId) {
    console.log(newSceneId);
    client.changeScene(newSceneId);
});

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

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