简体   繁体   English

socket.io不接收/发送

[英]socket.io not recieving/sending

I have a simple setup where I have some draggable divs and I want to use sockets.io to update the position between clients. 我有一个简单的设置,其中有一些可拖动的div,我想使用sockets.io更新客户端之间的位置。

On my client (index.html) I have : 在我的客户(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();
            });


        }

    }

My server is then : 我的服务器是:

    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');
    });

The server however doesn't seem to receive any information. 但是,服务器似乎未收到任何信息。 Is there something I'm doing wrong? 我做错了什么吗? Any help would be much appreciated! 任何帮助将非常感激!

In your client you need to define socket. 在您的客户端中,您需要定义套接字。

var socket = io();

Also, make sure you are including socket.io-xxxjs prior to calling socket.io in your javaScript. 另外,在javaScript中调用socket.io之前,请确保包括了socket.io-xxxjs。 You are probably already doing this, but it's unclear without seeing more code. 您可能已经在执行此操作,但是不清楚是否需要查看更多代码。

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

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