2017-01-19 1 views
1

저는 socket.io 또는 node.js가 새로 도입되었으므로 사용자가 연결하거나 연결을 끊을 때 메시지를 대화방에 인쇄하는 방법을 알고 싶었습니다. 이 사이트를 검색 할 때 일부 답변이 작동하지 않았고 다른 일부는 내 시나리오가 아니므로 작동하지 못했습니다.
하는 index.jssocket.io - 사용자가 연결하거나 연결을 끊을 때 메시지를 인쇄합니다.

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

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

io.on('connection', function(socket){ 
socket.on('chat message', function(msg){ 
    io.emit('chat message', msg); 
}); 
}); 

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

Index.html을

<!doctype html> 
<html> 
    <head> 
    <title>Derpzy.ML</title> 
    <style> 
    * { margin: 0; padding: 0; box-sizing: border-box; } 
     body { font: 13px Helvetica, Arial; } 
    form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } 
    form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; } 
    form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } 
    #messages { list-style-type: none; margin: 0; padding: 0; } 
    #messages li { padding: 5px 10px; } 
    #messages li:nth-child(odd) { background: #eee; } 
</style> 
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" /> 
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" /> 
    </head> 
    <body> 
<ul id="messages"></ul> 
<form action=""> 
    <input id="m" autocomplete="off" /><button>Send</button> 
</form> 
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> 
<script src="http://code.jquery.com/jquery-1.11.1.js"></script> 
<script> 
var socket = io(); 
$('form').submit(function(){ 
    socket.emit('chat message', $('#m').val()); 
    $('#m').val(''); 
    return false; 
}); 
socket.on('chat message', function(msg){ 
    $('#messages').append($('<li>').text(msg)); 
}); 
</script> 
    </body> 
</html> 

답변

0

테스트하지 않았하지만 당신이 그런 짓을 할 것입니다.

서버 측 :

//when socket is connected 
io.on('connection', function(socket){ 

    console.log('Yay, connection was recorded') 

    //emit message to all front-end clients 
    io.emit('chat message', 'some message sent to all users'); 

    //handling disconnects 
    socket.on('disconnect', function() { 
     io.emit('chat message', 'some user disconnected'); 
    }); 

}); 

클라이언트 측 :

//on io.emit from backend (notice 'chat message' event has same name as server side) 
socket.on('chat message', function(msg){ 

    console.log('Yay, I got a message back from the server: ', msg) 

    //handle the message however you would like 
    $('#messages').append($('<li>').text(msg)); 

}); 

서버를 테스트하려면, 당신은 백엔드 연결을 따기 보장하기 위해 '연결'콜백 내에서 CONSOLE.LOG 수 있습니다.

클라이언트를 테스트하려면 '채팅 메시지'콜백 내에서 로그를 콘솔하여 데이터가 수신되고 있는지 확인할 수 있습니다. 또한 DOM에 데이터를 추가하는 방법에 오류가 없는지 개발자 콘솔을 확인하십시오.

+0

아, 아주 잘 작동합니다! – TheAwesomeMutant

관련 문제