달력

5

« 2024/5 »

  • 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

사전 준비

node.js 설치(npm 설치)

socket.io 설치


서버 코드(server.js)

var http = require('http');

var fs = require('fs');

var socketio = require('socket.io');


var server = http.createServer(function(req, res){

fs.readFile('client.html', 'utf8', function(error, data){

res.writeHead(200, {'Content-Type':'text/html; charset=UTF-8'});

res.end(data);

});

}).listen(3000, function(){

});


var io = socketio.listen(server);

io.sockets.on('connection', function(socket){

socket.on('toServer', function(data){

socket.broadcast.emit('toClient', data);

});

});

서버로 클라이언트가 connection을 해오면 해당 소켓에 toServer라는 이벤트를 바인딩해 준다.

toServer라는 이벤트가 발생하면 broadcast로 모든 클라이언트에게 뿌려 준다.



클라이언트 코드(client.html)

<html>

<head>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script src="/socket.io/socket.io.js"></script>

<style>

#result{

width:400px;

height:300px;

background-color:darkgray;

border-style:solid;

border-width:1px;

}

</style>

</head>

<body>

<div id="result"></div>

<input id="input">

<button>Enter</button>

<script>

$(function(){

var socket = io.connect();

$("button").on("click", function(data){

$('#result').append('<div>나:'+$('#input').val()+'</div>');

socket.emit('toServer', $('#input').val());

$("#input").val('');

checkOverFlowBox();

});

socket.on('toClient', function(data){

$('#result').append('<div>익명:'+data+'</div>');

checkOverFlowBox();

});

$("input").on("keydown", function(e){

if(e.keyCode == 13){

$("button").trigger("click");

}

});

});

//줄 수 체크

var checkOverFlowBox = function(){

divLength = $('#result > div').length;

if(divLength >= 15){

$('#result > div').first().remove();

}

};

</script>

</body>

</html>

/socket.io/socket.io.js는 저절로 만들어짐.

저걸 쓰거나 아니면 socket.io의 클라이언트용 cdn을 써도 된다.

script src로 socket.io 사용준비를 끝냈으면 이제 io.connect()이 반환해주는 Socket객체가 가지고 있는 emit(서버로 전송)과 on(서버로부터 수신)을 사용할 수 있다.



뼈대가 되는 코드만 저장해두려고 작성함.

인터페이스와 디자인은 무시!

:
Posted by 클레잇