gpt4 book ai didi

javascript - socket.io 未接收/发送

转载 作者:行者123 更新时间:2023-12-03 04:37:26 36 4
gpt4 key购买 nike

我有一个简单的设置,其中有一些可拖动的 div,我想使用 sockets.io 来更新客户端之间的位置。

在我的客户端(index.html)上我有:

    // find the elements
var elements = document.getElementsByClassName('ball'),
labelsX = document.getElementsByClassName('coords-x'),
labelsY = document.getElementsByClassName('coords-y');

// loop over the 3 items...
for (var n = elements.length; n--;) {

// ... augment our default options with individual `onDrag` handlers
var opts = {
onDrag: onDragFactory(n),
setCursor: true
};

// ... and initialize drag for each
window.d = new Draggable(elements[n], opts);
console.log('ddd');
}

// bind `n` to its value at iteration time
function onDragFactory (n) {

return function (element, x, y) {

//This doesnt seem to work
console.log(elements[n].style.top);
socket.emit('positionx', elements[n].style.top);


socket.on('positionx', function(positionx){
elements[n].style.top= positionx.value();
});


}

}

我的服务器是:

    var express = require('express');
var path = require('path');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var publicPath = path.resolve(__dirname, 'public');

app.use(express.static(publicPath));

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});



//Server Side Listen for an event from the client
io.on('connection', function(socket){

socket.on('positionx', function(positionx){
console.log('recieving');
console.log(positionx);

io.emit('positionx', positionx);
});

});

http.listen(3000, function(){
console.log('listening on *:3000');
});

但是服务器似乎没有收到任何信息。我做错了什么吗?任何帮助将不胜感激!

最佳答案

在您的客户端中,您需要定义套接字。

var socket = io();

此外,请确保在 JavaScript 中调用 socket.io 之前包含了 socket.io-x.x.x.js。您可能已经这样做了,但如果没有看到更多代码,还不清楚。

关于javascript - socket.io 未接收/发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43233479/

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