반응형
nodejs -- socket.io 1.3.7 + jquery 예제 만들기
환경 : socket.io 1.3.7, jquery , 맥 요세미티, WebStorm 10.0.4
http://socket.io/get-started/chat/
여러명의 사용자가 nickname 으로 접속하기.
<< 소스 >>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
반응형
'nodejs' 카테고리의 다른 글
nodejs -- Formidable 사용하여 multiple file upload 하기 (0) | 2016.03.21 |
---|---|
nodejs -- nodejs 4.3.0 LTS 로 update 하기 (0) | 2016.02.15 |
nodejs -- socket.io, express-generator 시작 설정하기 (0) | 2015.11.30 |
nodejs -- MongoDB 연동 (0) | 2015.11.08 |
nodejs -- mysql 연동 (0) | 2015.11.08 |