테스트 사이트 - 개발 중인 베타 버전입니다

간단한 채팅

· 2년 전 · 1283

간단한 노드 채팅 예제입니다

 

1. 노드설치 후, 서버 js 실행

// server.js
var express = require('express');
var app = express();
var http = require('http').Server(app); //1
var io = require('socket.io')(http);    //1

app.get('/',function(req, res){  //2
  res.sendFile(__dirname + '/client.html');
});

var count=1;
io.on('connection', function(socket){ //3
  console.log('user connected: ', socket.id);  //3-1
  var name = "user" + count++;                 //3-1
  io.to(socket.id).emit('change name',name);   //3-1

  socket.on('disconnect', function(){ //3-2
    console.log('user disconnected: ', socket.id);
  });

  socket.on('send message', function(name,text){ //3-3
    var msg = name + ' : ' + text;
    console.log(msg);
    io.emit('receive message', msg);
  });
});

http.listen(3000, function(){ //4
  console.log('server on!');
});


2. 메세지 입력 화면

// client.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Chat</title>
    <style>
      .chat_log{ width: 95%; height: 200px; }
      .name{ width: 10%; }
      .message{ width: 70%; }
      .chat{ width: 10%; }
    </style>
  </head>
  <body>
    <div>
      <textarea id="chatLog" class="chat_log" readonly></textarea>
    </div>
    <form id="chat">
      <input id="name" class="name" type="text" readonly>
      <input id="message" class="message" type="text">
      <input type="submit" class="chat" value="chat"/>
    </form>
    <div id="box" class="box">
    <script src="/socket.io/socket.io.js"></script> <!-- 1 -->
    <script src="//code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      var socket = io(); //1
      $('#chat').on('submit', function(e){ //2
        socket.emit('send message', $('#name').val(), $('#message').val());
        $('#message').val('');
        $('#message').focus();
        e.preventDefault();
      });
      socket.on('receive message', function(msg){ //3
        $('#chatLog').append(msg+'\n');
        $('#chatLog').scrollTop($('#chatLog')[0].scrollHeight);
      });
      socket.on('change name', function(name){ //4
        $('#name').val(name);
      });
    </script>
  </body>
</html>

 

상세설명
https://onlyfor-me-blog.tistory.com/99

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시글 목록

번호 제목
17443
17442
17441
17440
17438
17436
17435
17433
17432
17430
17426
17416
17413
17401
17391
17379
17375
17374
17362
17350
17348
17341
17339
17335
17334
17333
17332
17331
17330
17329