반응형

nodejs -- socket.io 1.3.7 + jquery 예제 만들기


환경 : socket.io 1.3.7, jquery , 맥 요세미티, WebStorm 10.0.4


참고 : https://openclassrooms.com/courses/des-applications-ultra-rapides-avec-node-js/socket-io-passez-au-temps-reel

          http://socket.io/get-started/chat/




여러명의 사용자가 nickname 으로 접속하기.




<< 소스 >>


var http = require('http');
var fs = require('fs');
var server = http.createServer(function(req, res) {
fs.readFile('./index.html', 'utf-8', function(error, content) {
res.writeHead(200, {"Content-Type": "text/html"});
res.end(content);
});
});
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
console.log('connected...' + socket.id);
socket.emit('message', 'you are logged in !');
socket.broadcast.emit('message', 'another client just logged in! ');
socket.on('nickname', function(nickname) {
socket.nickname = nickname;
});
socket.on('message', function (message) {
console.log(socket.nickname + ' -- ' + socket.id +'; tells me he said to me : ' + message);
});
});
server.listen(3000, function(){
console.log("sever at http://127.0.0.1:3000")
});
view raw app.js hosted with ❤ by GitHub
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Socket.io</title>
</head>
<body>
<h1>Communication with socket.io !</h1>
<p><input type="button" value="bother server" id="poke" /></p>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
console.log('socket conneted....');
var nickname = prompt('nickname ?');
socket.emit('nickname', nickname);
socket.on('message', function(message) {
alert('The server has a message for you : ' + message);
})
$('#poke').click(function () {
socket.emit('message', 'server Hi, are you?');
})
</script>
</body>
</html>
view raw index.html hosted with ❤ by GitHub








반응형
Posted by 자유프로그램
,