Programming/node.js2014.09.15 15:49

Node.js 책 잠시 보고 만든 샘플입니다.

그냥 참고용으로!!ㅎㅎ


1. Server Side Node.js Socket.io

  1. var io = require('socket.io').listen(80);
  2. var clients = {};
  3. io.sockets.on('connection', function (socket){
  4. //입장 및 닉네임체크
  5. socket.on('create_nickname',function(nickname,returnFunction){
  6. //닉네임중복체크
  7. var returnCode = 1;
  8. for ( var i in clients ){
  9. if ( clients[i] == nickname ){
  10. returnCode = -1;
  11. break;
  12. }
  13. }
  14. //닉네임체크확인 결과 전달
  15. returnFunction(returnCode);
  16. //닉네임체크 유효화됨
  17. if ( returnCode == 1 ) {
  18. //클라이언트 닉네임등록
  19. clients[socket.id] = nickname;
  20. //새접속자로인한 전체 유저리스트 전달함
  21. io.sockets.emit('user_list',clients);
  22. //전체유저 메세지전송
  23. io.sockets.emit('msgPush',{"nickname":"시스템","msg":clients[socket.id]+" 유저가 입장하셨습니다."});
  24. console.log('CONNECT : ',nickname+' ['+socket.id+'] '+'('+Object.keys(clients).length+'명)');
  25. }
  26. });
  27. socket.on('msgSend',function(data){
  28. //자신을 제외한 전체유저에게 메세지전송
  29. socket.broadcast.emit('msgPush',data);
  30. /*
  31. *socket.emit('msgPush',data);//자신에게만 보낼때
  32. *socket.broadcast.emit('msgPush',data);//자신제외 전체유저
  33. *io.sockets.emit('msgPush',data);//자신포함 전체유저에게
  34. *io.sockets.in(socket_id).emit('msgPush',data);//특정유저에게 귓속말시 socket_id추가입력하면됨
  35.     *io.of('namespace').emit('msgPush', data); //of 지정된 name space의 유저
  36. */
  37. console.log('Chat Msg : ','['+data['nickname']+'] '+data['msg']);
  38. });
  39. //접속종료시처리
  40. socket.on('disconnect', function(){
  41. if ( clients[socket.id] ){
  42. //유저이탈 메세지전달
  43. io.sockets.emit('msgPush',{"nickname":"시스템","msg":clients[socket.id]+" 유저가 나가셨습니다."});
  44. console.log('DISCONNECT : ', clients[socket.id]);
  45. //이탈유저닉네임삭제
  46. delete clients[socket.id];
  47. //유저이탈 전체유저리스트 갱신
  48. io.sockets.emit('user_list',clients);
  49. }else{
  50. console.log('NOT USER DISCONNECT : ', socket.id);
  51. }
  52. });
  53. });


2. Client

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Chat</title>
  6. </head>
  7. <body>
  8. <div id="chatJoin">
  9. <form id="chatJoinForm">
  10. 대화명 : <input id="nickname" name="nickname" type="text"> <input type="submit" value="입장">
  11. </form>
  12. </div>
  13. <div id="chatRoom" style="display:none;">
  14. <div id="msgList" style="float:left;width:500px;height:300px;border:1px solid #1D365D;overflow:auto;"></div>
  15. <div style="float:left;width:100px;height:300px;border:1px solid #1D365D;margin-left:3px;">
  16. <div style="border-bottom:1px solid #1D365D;">접속자</div>
  17. <div id="userList"></div>
  18. </div>
  19. <div style="clear:both;">
  20. <form id="chatMsgForm">ChatMsg : <input id="msgText" name="msg" type="text"> <input type="submit" value="전송"></form>
  21. </div>
  22. </div>
  23. </body>
  24. <script type="text/javascript" src="jquery-1.11.1.min.js"></script>
  25. <script type="text/javascript" src="socket.io.js"></script>
  26. <script type="text/javascript">
  27. $(function(){
  28. var socket;
  29. function createNickname(nickName){
  30. socket.emit('create_nickname',nickName,function(returnCode){
  31. if ( returnCode == 1 ){
  32. //정상적인 닉네임
  33. $('#chatJoin').hide();
  34. $('#chatRoom').show();
  35. $('#msgText').focus();
  36. }else{ //아니면 닉네임중복됨
  37. alert('존재하는 닉네임입니다.');
  38. $('#nickname').focus();
  39. socket.disconnect();
  40. }
  41. });
  42. }
  43. function msgAdd(data){
  44. var sHtml = '<div><span style="color:blue;">'+data['nickname']+'</span> : '+data['msg']+'</div>';
  45. $('#msgList').append(sHtml);
  46. $("#msgList").scrollTop($("#msgList")[0].scrollHeight);
  47. }
  48. $('#chatMsgForm').submit(function(event){
  49. event.preventDefault();
  50. var data = {"nickname":$('#nickname').val(),"msg":$('#msgText').val()}
  51. msgAdd(data);
  52. $('#msgText').val('');
  53. $('#msgText').focus();
  54. //서버에 입력메세지전달
  55. socket.emit('msgSend', data);
  56. });
  57. $('#chatJoinForm').submit(function(event){
  58. event.preventDefault();
  59. if ( !$('#nickname').val() ){
  60. alert("닉네임을 입력해주세요");
  61. $('#nickname').focus();
  62. return false;
  63. }
  64. /*
  65. *https://github.com/automattic/socket.io-client
  66. */
  67. socket = io.connect('http://127.0.0.1', {'forceNew':true,reconnection:false});
  68. socket.on('connect', function () {
  69. createNickname($('#nickname').val());
  70. });
  71. socket.on('user_list',function(clients){
  72. //심플테스트 버젼이라서 삭제하고 새로 갱신하는방안
  73. $('#userList').html('');
  74. for ( var i in clients ){
  75. if ( clients[i] == $('#nickname').val() ){
  76. sHtml = '<div style="font-weight:bold;">'+clients[i]+'</div>';
  77. }else{
  78. sHtml = '<div>'+clients[i]+'</div>';
  79. }
  80. $('#userList').append(sHtml);
  81. }
  82. });
  83. socket.on('msgPush',function(data){
  84. msgAdd(data);
  85. });
  86. socket.on('disconnect', function(){
  87. $('#msgList').html('');
  88. $('#nickname').val('');
  89. $('#chatJoin').show();
  90. $('#chatRoom').hide();
  91. alert('Server Disconnect');
  92. });
  93. socket.on('connect_error', function (data) {
  94. alert('CONNECT_ERROR : '+data);
  95. });
  96. });
  97. });
  98. </script>
  99. </html>


Posted by 시니^^

티스토리 툴바