2010-11-28 5 views
2

저는 다중 사용자 스케치북을 만들고 현재 연결된 모든 사용자의 업데이트 된 목록을 가져오고 유지하는 데 문제가 있습니다. 나는 새로운 고객의 모든 기존 고객에게 알리고, 기존 클라이언트를 새로 연결된 고객에게 전달하는 가장 좋은 방법을 찾고있다. 이 작업을 수행하려는 이유는 한 클라이언트가 선을 그릴 때 모든 다른 클라이언트가 목록에서 해당 클라이언트를 찾은 다음 해당 선 배열을 각 배열에 추가하기 때문입니다.웹 소켓을 사용하는 클라이언트 목록 얻기

Server.js

var sys = require("sys"); 
var ws = require('websocket-server'); 

var server = ws.createServer({debug: true}); 

server.addListener("connection", function(conn) { 
// When a message is received, broadcast it too all the clients 
// that are currently connected. 
conn.send('NEW_SERVER_MESSAGE:Welcome!'); 
conn.send('USER_CONNECTED:' + conn.id); 

conn.addListener("message", function(msg){ 
    switch(msg) { 
     case 'GET_ALL_ACTIVE_USERS': 
      server.manager.forEach(function(con) { 
       conn.broadcast('USER_CONNECTED:' + con.id); 
      }); 
      break; 
     case 'UPDATE_CURSOR': 
      conn.broadcast(msg + '_' + conn.id); 
      break; 
     default: 
      conn.broadcast(msg); 
      break; 
    } 

}); 
conn.addListener('close', function(msg) { 
    conn.broadcast('USER_DISCONNECTED:' + conn.id); 
}); 
}); 

server.addListener("error", function(){ 
console.log(Array.prototype.join.call(arguments, ", ")); 
}); 

server.addListener("listening", function(){ 
console.log("Listening for connections..."); 
}); 

server.addListener("disconnected", function(conn){ 
console.log("<"+conn.id+"> disconnected."); 
}); 

server.listen(8002);</code> 

내 JS 네트워크 번호 : 순간

sketchPadNet = function (b,s) { 
var self = this; 

this.host = "ws://localhost:8002/server.js"; 

this.id = null; 
this.users = []; 
this.heightOffset = 53; 
this.scene = s; 
this.connected = b; 

var User = function(id) { 
    this.id = id; 
    this.nickname = id; 
    this.lines = []; 
    this.position = ""; 
}; 

this.init = function() { 
    try { 
     socket = new WebSocket(self.host); 
     socket.onopen = function (msg) { 
      socket.send('GET_ALL_ACTIVE_USERS'); 
     }; 

     socket.onmessage = function (msg) { 
      var m = msg.data.split(':'); 
      switch(m[0]) { 

      case 'USER_CONNECTED': 
       console.log('USER_CONNECTED'); 
       var u = new User(m[1]); 
       u.lines = []; 
       u.nickname = u.id; 
       self.users.push(u); 
       console.log(self.users.length); 
       console.log(self.users); 
       break; 

      case 'USER_DISCONNECTED': 
       console.log('USER_DISCONNECTED'); 
       for(var i = 0; i < self.users.length; ++i) { 
        console.log(self.users[i]); 
        if(m[1] == self.users[i].id) { 
         self.users.splice(i, 1); 
        } 
       } 
       break; 

      case 'DRAW_LINE': 
       var tmpMsg = m[1].split('_'); 

       var id = tmpMsg[8]; 
       var userIndex = ''; 

       for(var i = 0; i < self.users.length; ++i) { 
        if(self.users[i].id == id) userIndex = i; 
       } 

       var p1 = (self.users[userIndex].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[userIndex].lines[self.users[userIndex].lines.length - 1].point2; 
       var p2 = new BLUR.Vertex3(tmpMsg[3], tmpMsg[4], tmpMsg[5]); 

       var line = new BLUR.Line3D(p1, p2, tmpMsg[7]); 
       line.material = tmpMsg[6]; 

       // add the newly created line to the scene. 
       self.scene.addObject(line); 
       self.users[userIndex].lines.push(line); 
       break; 

      case 'UPDATE_CURSOR': 
       for(var i = 0; i < self.scene.objects.length; ++i) { 
        if(self.scene.objects[i].type == 'BLUR.Particle') 
         self.scene.removeObject(scene.objects[i]); 
       } 

       var coords = m[1].split('_'); 
       var id = coords[2]; 
       var userIndex = 0; 

       for(var i = 0; i < self.users.length; ++i) { 
        if(self.users[i].id == id) 
         userIndex = i; 
       } 

       self.users[userIndex].position = new BLUR.Vertex3(coords[0], coords[1], 1); 
       var p = new BLUR.Particle(self.users[userIndex].position, 4); 
       p.material = new BLUR.RGBColour(176,23,31,0.3); 

       self.scene.addObject(p); 
       break; 

      case 'RECEIVE_ID': 
       self.id = m[1]; 
       self.connected.nicknameObj.text = self.id; 
       console.log(self.id); 
       break; 

       break; 
      } 
     }; 

     socket.onclose = function (msg) { 
      // feck! 
      self.connected.addServerError('Server disconnected, try refreshing.'); 
     }; 
    } 
    catch (ex) { 
     console.log('EXCEPTION: ' + ex); 
    } 
}; 

은, 새로운 클라이언트가 접속 될 때 메시지를 전송하고, 어레이에 첨가하고, 상기 역방향 클라이언트가 연결을 끊을 때 이것이 업데이트를 유지하고 있지는 않지만 어떤 이유로? 내가 여기 믿을 수 없을만큼 바보 야하는 경우

Uncaught TypeError: Cannot read property 'lines' of undefined 

죄송합니다,하지만 어떤 도움이 감사합니다! : 클라이언트가 선을 그릴 때 예를 들어, 다른 사람의 일부는이 오류를보고

건배 :)

+0

그래서 서버 측에서 자바 스크립트를 사용하고 있습니까? 어떤 종류의 프레임 워크/컨테이너를 사용하고 있습니까? –

+0

Im는 Node.js를 https://github.com/miksago/node-websocket-server와 함께 사용하고 있습니다. – harrynorthover

답변

2

내가 코드를보고 있지만 오류가 표시되는 경우에도 행 번호없이 그것을 알아 내려고 시도, 그것은 어쨌든 꽤 어렵다.

conn.send('USER_CONNECTED:' + conn.id); // send the connect message to ONE user 
conn.broadcast('USER_DISCONNECTED:' + conn.id); // send the disconnect to ALL users 

은 그래서 사용자가 연결할 때 당신은 단순히 방송 전화를 놓치고있는 것 같다 :

나는이 문제는 여기에 가정하자.

0

확인 실제 문제는 클라이언트 쪽 'DRAW_LINE' 인 것 같습니다. 모든 사용자에게 메시지를 브로드 캐스트하고 클라이언트에 메시지를 다시 보내지 않았습니까? 클라이언트 코드에서이 라인에

오류 지점 :

var p1 = (self.users[userIndex].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[userIndex].lines[self.users[userIndex].lines.length - 1].point2; 

'DRAW_LINE'의 서버 코드를 입력하십시오. 문제는 분명히 거기에 자르지 만 다른 어떤 것에는 없다.

또한 self.users[userIndex]undefined입니다. 그 사용자가 존재하지 않을 수도 있습니까?

for 루프가 필요한 이유는 무엇입니까? 왜 그냥 :

if(self.users[id] != undefined) { 
    var p1 = (self.users[id].lines.length < 1) ? new BLUR.Vertex3(tmpMsg[0], tmpMsg[1], tmpMsg[2]) : self.users[id].lines[self.users[id].lines.length - 1].point2; 
} 
0

I'm trying to find the best way to notify all existing clients of a new client, and passing the existing clients to the newly connected one

내가 대신 socket.io 좀보고 당신을 조언한다. 브라우저에서 웹 소켓을 지원하지 않는 경우이를 쉽게 수행하고 다른 사용 가능한 전송으로 장애를 복구 할 수 있습니다.

0

객실 및 사용자 목록이 내장 된 기존 서버를 사용하는 것이 좋습니다.비교를 위해, 여기 연합 서버 사용하는 자바 스크립트로 작성된 다중 사용자 스케치를위한 튜토리얼입니다 : 여기

http://www.unionplatform.com/?page_id=2762

및/떠나 객실에 합류 객실과 고객을위한 메시징 시스템에 대한 설명을 포함하고 연합 서버의 문서화 된 프로토콜은이다 :

http://unionplatform.com/specs/upc/

당신에게 몇 가지 아이디어를 줄 수도 있습니다.

콜린

관련 문제