[NodeJs] Socket.io를 이용한 채팅구현

[NodeJs] Socket.io를 이용한 채팅구현 updated_at: 2024-01-23 12:02

Socket.io 를 활용한 간단한 채팅구현

express와 socket-io를 활용한 간단한 채팅 예제입니다.

샘플 1

js

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);

const path = require('path');

app.get('/', (req, res) => {
   res.send('Welcome To Node Project');
});

app.route('/chat')
    .get((req, res) => {
        res.sendFile(path.join(__dirname, '/public/chat.html'));
    })
    .post((req, res) => {
        res.send('Add a book');
    })

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });

  socket.on('message', (msg) => {
    console.log('message: ' + msg);
  });
});

http.listen(3000, () => {
  console.log('listening on *:3000');
});

html

<html>
  <head></head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

<script src="/socket.io/socket.io.js"></script>
<script>
$(function () {
  var socket = io();
  $('form').submit(function(e) {
    e.preventDefault(); // prevents page reloading
    socket.emit('message', $('#m').val());
    $('#m').val('');
    return false;
  });
});
</script>

  </body>
</html>

샘플 2

js

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const path = require('path');

app.get('/', (req, res) => {
  res.send('Welcome To Node Project');
});

app.route('/chat')
  .get((req, res) => {
    res.sendFile(path.join(__dirname, '/public/chat-4-2.html'));
  })
  .post((req, res) => {
    res.send('Add a book');
  })

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('disconnect', () => {
      console.log('user disconnected');
  });

  socket.on('message', (msg) => {
    console.log('message: ' + msg);
  });
});

http.listen(3000, () => {
  console.log('listening on *:3000');
});

html

<html>
  <head></head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

<script src="/socket.io/socket.io.js"></script>
<script>
$(function () {
  var socket = io();

  $('form').submit(function(e) {
    e.preventDefault(); // prevents page reloading
    socket.emit('message', $('#m').val());
    $('#m').val('');
    return false;
  });

  socket.on('message', function(msg){
    $('#messages').append($('<li>').text(msg));
  });
});
</script>

  </body>
</html>

평점을 남겨주세요
평점 : 5.0
총 투표수 : 1

질문 및 답글