tmp

간단한 채팅

· 2023-02-15 (수) 09:03:30 · 2099

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

 

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

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

개발자팁

5,403건

개발과 관련된 유용한 정보를 공유하세요. 질문은 QA에서 해주시기 바랍니다.

+
분류 제목 글쓴이 날짜 조회
MySQL 21-04-20 조회 2,527
기타 21-04-18 조회 3,399
MySQL 21-04-17 조회 2,697
MySQL 21-04-16 조회 2,391
MySQL 21-04-15 조회 2,199
MySQL 21-04-15 조회 2,008
OS 21-03-31 조회 5,316
웹서버 21-03-24 조회 2,873
웹서버 21-03-18 조회 2,875
웹서버 21-03-11 조회 3,107
웹서버 21-03-08 조회 2,410
웹서버 21-03-02 조회 2,863
웹서버 21-03-02 조회 3,242
MySQL 21-02-25 조회 3,663
웹서버 21-02-17 조회 8,154
웹서버 21-02-13 조회 2,266
OS 21-01-20 조회 7,445
PHP 21-01-12 조회 5,375
JavaScript 21-01-12 조회 3,022
MySQL 20-11-27 조회 4,537
MySQL 20-11-25 조회 3,731
PHP 20-11-24 조회 2,990
PHP 20-11-23 조회 3,972
PHP 20-11-19 조회 5,052
PHP 20-11-13 조회 5,294
웹서버 20-09-26 조회 7,939
기타 20-08-07 조회 5,868
MySQL 20-08-05 조회 3,924
기타 20-07-15 조회 2,978
기타 20-07-14 조회 3,575