2011-10-14 3 views
2

socket.io Google 그룹에서이 질문을했지만 아무도 나를 도와 줄 수 없었습니다. 클라이언트 측에서이 코드 가지고 있지만socket.io 간단한 채팅 구현

var chat = io 
    .of('/chat') 
    .on('connection', function (socket) { 
    socket.emit('message', { 
     that: 'only' 
     , '/chat': 'will get' 
    }); 
    }); 

chat.on("message", function(data){ 
    console.log(data); 
}); 

:

var chat = io.connect('http://localhost/chat'); 

    chat.on('message', function (data) { 
    chat.emit('hi!'); 
    }); 

    chat.emit("message", {"this": "is a message"}); 

콘솔을 내가에서 첫 번째 메시지 것을 볼 수 있습니다

나는 서버 측에이 코드 조각이 서버가 전송되었지만 일단 연결되어 메시지를 수신하면 클라이언트처럼 보이지만 'hi!' 메시지를 내 보내지 않습니다. 게다가 클라이언트가 또 다른 메시지, 즉 붙여 넣은 마지막 줄을 내 보내길 원합니다. 또한이 메시지는 서버에 의해 수신되지 않습니다 (이론적으로는 로그에 기록해야 함).

저는 분명히 뭔가 잘못하고 있습니다. 정확히 어디에서 이런 일이 일어나고 있는지 지적 해 줄 수 있습니까? 내가 결국 달성하고자하는 것은 단순한 채팅과 유사한 시스템을 설정하는 것입니다. 그러나 실제로 채팅 자체를 작성하기 전에이 물건 (채널)을 사용하고 싶습니다. 감사합니다

답변

1

이유는 "안녕하세요"를하지가 않는 이유 보내지 않은 것은 .emit의 첫 번째 인수가 여기에있는 "hi"라는 이벤트 이름이기 때문입니다.

.on('hi',function(data){ 
    console.log(data) // should log "undefined" 
}); 

또한 할 수 있습니다 당신은 서버 측에서 다음을 수행 기술적 경우, 나는 (당신이 객체가 전송 될 두 번째 인수로 아무것도 넣지 않았기 때문에) 정의되지 않은 데이터를 얻을해야한다고 생각 웹 소켓 의미와 비슷한 .send을 사용하고 message 이벤트로 보냅니다. 클라이언트 측에서 .emit.send으로 변경하면 정상적으로 작동합니다. 요약

:

.emit('eventName', 'data') // sends to the eventName name 
.send('data') // sends to message event 

작업을 클라이언트 측 코드 :

var chat = io.connect('http://localhost/chat'); 

    chat.on('message', function (data) { 
    chat.send('hi!'); 
    }); 

    chat.emit("message", {"this": "is a message"}); 
1

나는 조금 내려 무식하지만 :

서버 :

var io = require('socket.io').listen(8080); 

var chat = io 
    .of('/chat') 
    .on('connection', function (socket) { 
    socket.send('welcome to the interwebs'); 
    socket.on('message', function(data) { 
     console.log(data); 
    }); 
    }); 

클라이언트 :

<html> 
<body> 
<script src="http://10.120.28.201:8080/socket.io/socket.io.js"></script> 
<script type="text/javascript"> 
var chat = io.connect('http://10.120.28.201:8080/chat'); 

    chat.on('connect', function() { 
    console.log("connected"); 
    chat.send('hi!'); 
    chat.on('message', function (data) { 
     console.log(data); 
    }); 
    }); 

</script> 
</body> 
</html>