gpt4 book ai didi

javascript - Socket.io : "Cannot read property ' emit' of undefined"

转载 作者:太空宇宙 更新时间:2023-11-04 02:49:36 25 4
gpt4 key购买 nike

所以我目前正在使用 socket.io 开发我的网站。

今天,当我实现套接字时,我遇到了一个不错的小错误“无法读取未定义的属性'emit'”我找不到我的代码有什么问题,所以我希望你们能帮助我。

App.js:

var socket  = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = 9999;

server.listen(port, function () {
console.log('Listening at port %d', port);
});

io.sockets.on('connection', function (socket) {
console.log('User connected');

socket.on('create_socket', function(port){
console.log(port);
});

客户端:

<div>
<p class="connected" hidden>Connected port : 9999</p>
<p class="connect_error" hidden><strong>Can not connect to socket on port 9999</strong></p>
</div>

<script>
var socket = io.connect("http://localhost:9999");

// If connection can not be established
socket.on('connect_error', function(socket) {
$('.connected').hide();
$('.connect_error').show();
});

// Connection established
socket.on('connect', function(socket) {
$('.connect_error').hide();
$('.connected').show();
// socket.on('create_socket', null, <?= $port; ?> );
socket.emit('create_socket', '<?= $port; ?>');
});
</script>

顺便说一句,所有的 socket.io/jquery/... 包含都正确完成,即使它们没有出现在代码中

提前致谢

最佳答案

客户端代码:

改变

// Connection established
socket.on('connect', function(socket) {

// Connection established
socket.on('connect', function(data) {

最终:

// Connection established
socket.on('connect', function(data) {
$('.connect_error').hide();
$('.connected').show();
console.log(data);
socket.emit('create_socket', '<?= $port; ?>');
});

之前,您覆盖了套接字对象。

关于javascript - Socket.io : "Cannot read property ' emit' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37725948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com