簡體   English   中英

socket.io不接收/發送

[英]socket.io not recieving/sending

我有一個簡單的設置,其中有一些可拖動的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-xxxjs。 您可能已經在執行此操作,但是不清楚是否需要查看更多代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM