A Bidirectional Communication library for Building Real-time web applications
root-directory/
├── server.js
├── client.js
└── index.html
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: "http://127.0.0.1:9998", // 클라이언트 출처
methods: ["GET", "POST"],
credentials: true
}
});
app.use(cors({
origin: "http://127.0.0.1:9998",
methods: ["GET", "POST"],
credentials: true
}));
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('User disconnected');
});
socket.on('chat message', (msg) => {
msg += ": server";
console.log('Message: ' + msg);
io.emit('chat message', msg); // 모든 클라이언트에게 메시지 전송
});
});
server.listen(9999, () => {
console.log('Server is listening on port 9999');
});
const express = require('express');
const http = require('http');
const path = require('path');
const cors = require('cors');
const app = express();
const server = http.createServer(app);
app.use(cors());
app.use(express.static(path.join(__dirname, '/')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '/', 'index.html'));
});
server.listen(9998, () => {
console.log('Server is listening on port 9998');
});
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO chat</title>
<script src="http://127.0.0.1:9999/socket.io/socket.io.js"></script>
<script>
document.addEventListener("DOMContentLoaded", () => {
const socket = io('http://127.0.0.1:9999');
socket.on('chat message', (msg) => {
const item = document.createElement('li');
item.textContent = msg;
document.getElementById('messages').appendChild(item);
});
document.getElementById('form').addEventListener('submit', (e) => {
e.preventDefault();
const input = document.getElementById('input');
socket.emit('chat message', input.value);
input.value = '';
});
});
</script>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
Two browsers are sharing the same data