index.html : 클라이언트 부분 Client part
index.js : 서버부분 Server part
– 기본 채팅 프로그램입니다.
– 이전 포스트 부분을(실시간 통신) 잘 이해한다면 이번 부분도 크게 어렵지 않을 겁니다.
– 녹색 컬러로 강조된 부분은 소켓 통신 모듈과 관련 있는 부분입니다.
– 텍스트필드에 입력된 메세지를 소켓 통신으로 서버에 보내면 서버가 다시 모든 클라이언트에게 메세지를 보냅니다.
– input.focus() : 텍스트필드에 항상 포커스를 유지합니다.
– form.addEventListener(‘submit’, (e) => { } : Send버튼을 눌렀을때 submit(데이터전송)을 실행합니다.
– This is a basic chat program
– If you understand the previous post part (real-time communication) well, this part won’t be too difficult.
– The parts highlighted in green are related to the socket communication module.
– When you send the message entered in the text field to the server through socket communication, the server sends the message back to all clients.
– input.focus(): Always maintains focus on the text field.
– form.addEventListener(‘submit’, (e) => { }: Executes submit (data transfer) when the Send button is pressed.
// index.js
const express = require('express');
const { createServer } = require('node:http');
const { join } = require('node:path');
const { Server } = require('socket.io');
async function main() {
const app = express();
const server = createServer(app);
const io = new Server(server, {
connectionStateRecovery: {},
});
app.get('/', (req, res) => {
res.sendFile(join(__dirname, 'index.html'));
});
io.on('connection', async(socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
socket.on('chat message', async (msg) => {
io.emit('chat message', msg);
});
});
const port = process.env.PORT || 3000;
server.listen(port, () => {
console.log(`server running at http://localhost:${port}`);
});
}//end mail()
main();
// index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>chat</title>
</head>
<body>
<label>chat basic</label>
<ul id="messages"></ul>
<form id="form" action="">
<input type="text" id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
let counter = 0;
const socket = io();
const form = document.getElementById('form');
const input = document.getElementById('input');
const messages = document.getElementById('messages');
input.focus();
form.addEventListener('submit', (e) => {
console.log(input.value);
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
input.focus();
}
});
socket.on('chat message', (msg) => {
const item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
</body>
</html>