[NodeJs] Socket.io를 이용한 채팅구현
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>