티스토리 뷰
[chatting] redis pub/sub + socket.io를 이용한 chatting server & client
rocksea 2013. 8. 9. 18:02redis pub/sub + socket.io를 이용한 chatting server & client 만들기.
일단 초간단 합니다.
예전에 pub/sub model의 mosquitto라는 android용 push서버를 이용하여 개발한 적이 있어 그런지 이해가 빨리 된 것 같습니다.
pub/sub model에 관한 구조 이해.
메세지 패턴을 필터링하여 send/receive 하는 방식. (Java Message Service 및 예전에 android push서버 개발할때 mosquitto라는 서버가 pub/sub구조)
http://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern
환경설정
pub/sub모델을 쉽게 구현하기 위해 redis를 사용해야 하므로 redis를 우선 설치해야합니다. (아래 URL 참조)
step 1. code
var app = require('http').createServer(handler);
app.listen(8080);
var io = require('socket.io').listen(app);
var redis = require('redis');
var fs = require('fs');
function handler(req,res){
fs.readFile(__dirname + '/index.html', function(err,data){
if(err){
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
console.log("Listening on port 8080");
res.end(data);
});
}
var store = redis.createClient();
var pub = redis.createClient();
var sub = redis.createClient();
sub.subscribe("chatting");
io.sockets.on('connection', function (client) {
sub.on("message", function (channel, message) {
console.log("message received on server from publish ");
client.send(message);
});
client.on("message", function (msg) {
console.log(msg);
if(msg.type == "chat"){
pub.publish("chatting",msg.message);
}
else if(msg.type == "setUsername"){
pub.publish("chatting","A new user in connected:" + msg.user);
store.sadd("onlineUsers",msg.user);
}
});
client.on('disconnect', function () {
sub.quit();
pub.publish("chatting","User is disconnected :" + client.id);
});
});
<html>
<head>
<title>Socket and Redis in Node.js</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<div id="username">
<input type="text" name="usernameTxt" /> <input type="button" name="setUsername" value="Set Username" />
</div>
<div id="sendChat" style="display:none;">
<input type="text" name="chatTxt" /> <input type="button" name="sendBtn" value="Send" />
</div>
<br />
<div id="content"></div>
<script>
$(document).ready(function() {
var username = "anonymous";
$('input[name=setUsername]').click(function(){
if($('input[name=usernameTxt]').val() != ""){
username = $('input[name=usernameTxt]').val();
var msg = {type:'setUsername',user:username};
socket.json.send(msg);
}
$('#username').slideUp("slow",function(){
$('#sendChat').slideDown("slow");
});
});
var socket = new io.connect('http://127.0.0.1:80');
var content = $('#content');
socket.on('connect', function() {
console.log("Connected");
});
socket.on('message', function(message){
content.append(message + '<br />');
}) ;
socket.on('disconnect', function() {
console.log('disconnected');
content.html("<b>Disconnected!</b>");
});
$("input[name=sendBtn]").click(function(){
var msg = {type:'chat',message:username + " : " + $("input[name=chatTxt]").val()}
socket.json.send(msg);
$("input[name=chatTxt]").val("");
});
});
</script>
</body>
</html>
step 2. web browser를 이용한 채팅
각각의 다른 browser에서 rocksea 라는 사용자와 rockstar라는 채팅 사용자를 추가합니다.
(저는 chrome과 IE를 사용하였습니다)
[그림1] chrome을 통한 채팅 사용자 추가
[그림2] IE를 통한 채팅 사용자 추가
[그림3] 두 사용자 생성시 화면
step 3. 채팅
이제 메세지 입력 후 Send버튼을 이용해 전송하면 서로 상대의 browser에 메세지가 잘 전달 되고 있는 화면을 볼 수 있습니다.
[그림4] 채팅하기
5분도 안걸려서 채팅서버 완성.
참 쉽죠~??
.by rocksea
'Developer' 카테고리의 다른 글
| [jqeury] 자동완성 구현 ( auto-complete ) (2) | 2013.09.09 |
|---|---|
| [nginx] 자동 urldecoding문제 (0) | 2013.08.22 |
| [zookeeper] Coordinating Distributed Applications with ZooKeeper (2) | 2013.07.22 |
| [linux] access log 접속아이피 분석 (0) | 2013.07.18 |
| [gitlab] ruby version update ( gitlab start syntax error) (0) | 2013.07.15 |
- Total
- Today
- Yesterday
- Business English
- nodejs
- 비지니스 영어
- PostgreSQL
- hdfs
- 영작
- maven
- memcached
- mongoDB
- 다낭
- 조동사
- ubuntu
- 대명사 구문
- 비교구문
- it
- Python
- hadoop
- redis
- 스페인 여행
- NGINX
- 영문법
- 가정법
- JBOSS
- 해외여행
- Python Django
- 도덕경
- 여행
- k8s
- AWS
- 베트남
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |