– server_socket.js : 서버부분
– socket.html : 1초마다 카운터 실행,소켓을통해 카운터 값을 전송
– socCounter.html : 소켓통신을 통해서 서버로부터 카운터 값을 수신하여 화면에 표시
– server_socket.js : Server Part
– socket.html : Run counter every second, transmit counter value through socket
– socCounter.html : Receives the counter value from the server through socket communication and displays it on the screen.
– 소켓을 이용해서 실시간 통신을 구현하는 것은 예전부터 많이 사용하던 내용입니다.
– 예전에는 브라우저에서 실시간 통신을 구현하려면 자바,C#같은 기타 다른 프로그래밍 언어로 구현해야 했습니다.
– NODEJS는 이런 소켓통신을 브라우저에서 사용 할 수 있도록 해줍니다.
– 이런 소켓통신이 사용되는 곳은 우리가 흔히 보는 프로그램중에 채팅프로그램이나,주식차트,sns의 좋아요 등에서 볼 수 있습니다.
– 소켓이란 부분의 이해가 어렵다면 데이터베이스나 텍스트파일이라고 생각하세요
– Implementing real-time communication using sockets has been widely used for a long time.
– In the past, to implement real-time communication in browsers, it had to be implemented in other programming languages such as Java and C#.
– NODEJS allows this kind of socket communication to be used in the browser.
– Places where this type of socket communication is used can be found in chat programs, stock charts, social media likes, etc., among the programs we commonly see.
– If you have difficulty understanding the socket part, think of it as a database or text file.
1.설치 install
다음과 같이 모듈을 설치 할 수 있습니다.
You can install the module as follows
# npm install socket.io
2.서버부분 Server Part
– 중요한 코드 부분만 살펴 보겠습니다.
– io.on(‘connection’, (socket) => {} : 이 부분은 서버에서 소켓 접속을 기다리며 접속 될 경우 {} 내부의 코드를 실행 합니다.
– ‘connectiont’부분은 소켓 키 값으로 변수라고 생각하시면 됩니다.
– socket.on(‘message’, (msg) => {} : 소켓에서 카운터 값을 읽어 오는 부분입니다.
– io.emit(‘socMessage’, msg); : 이 부분이 소켓에 메세지(카운터 값)를 작성하는 부분입니다. 서버 소켓에 접속하면 모든 사용자가 이 메세지(카운터 값)을 읽을 수 있습니다.
– socket.on(‘disconnect’, () => {} : 이 부분은 사용자가 서버에서 접속 해제될 때 {] 이 부분의 코드가 실행됩니다.
– Let’s look at only the important parts of the code.
– io.on(‘connection’, (socket) => {}: This part waits for a socket connection from the server and executes the code inside {} when connected.
– You can think of the ‘connectiont’ part as a variable as the socket key value.
– socket.on(‘message’, (msg) => {}: This is the part that reads the counter value from the socket.
– This part is where a message (counter value) is written to the socket. Any user can read this message (counter value) by connecting to the server socket.
– socket.on(‘disconnect’, () => {} : This part of the code is executed when the user disconnects from the server {].
...
const { Server } = require('socket.io');
...
const io = new Server(server);
...
io.on('connection', (socket) => {
...
socket.on('socMessage', (msg) => {
console.log('socket count: ' + msg);
io.emit('socMessage', msg);
});
....
});
...
2.클라이언트 부분 Client part
– 클라이언트 부분은 socket.html과 socket.html부분입니다.
– <script src=”/socket.io/socket.io.js”></script> : html파일에서 소켓 모듈을 사용하는 부분입니다.
– 코드가 복잡해 보이지만 서버 부분과 중복됩니다.
– socket.on(‘message’, (msg) => {} : 소켓의 메세지를 읽는 부분입니다.
– socket.emit(‘socMessage’, i); : 소켓에 메세지를 작성하는 부분입니다.
– The client part is socket.html and socket.html part.
– This is the part that uses the socket module in the html file.
– The code may seem complicated, but it overlaps with the server part.
– socket.on(‘message’, (msg) => {}: This is the part that reads the message from the socket.
– socket.emit(‘socMessage’, i); : This is the part that writes a message to the socket.
...
<script src="/socket.io/socket.io.js"></script>
...
socket.on('message', (msg) => {
...
});
...
socket.emit('socMessage', i);
...
4.전체코드(Full Code)
server_socket.js
//server_socket.js
const http = require('http');
const express = require('express');
const { Server } = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = new Server(server);
/* routing */
// root
app.get("/",(req,res)=>{
res.sendFile(__dirname + "/socket.html");
});
// socCounter
app.get("/soccounter",(req,res)=>{
res.sendFile(__dirname + "/socCounter.html");
});
// socket connection
io.on('connection', (socket) => {
console.log('a user connected');
// user disconnet
socket.on('disconnect', () => {
console.log('user disconnected');
});
//client message
socket.on('message', (msg) => {
console.log('socket emit message: ' + msg);
io.emit('message', msg);
});
socket.on('socMessage', (msg) => {
console.log('socket count: ' + msg);
io.emit('socMessage', msg);
});
});
// Start the server
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`CommonJS(Express) Server is running on port ${PORT}`);
});
socket.html
<html>
<head>
<title>
socket test
</title>
</head>
<body>
<!-- socket message -->
<ul id="messages"></ul><br>
<ul id="countmsg"></ul><br>
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
const messages = document.getElementById('messages');
const countermsg = document.getElementById('countmsg');
const socket = io();
socket.emit('message', 'Hello Socket!!');
socket.on('message', (msg) => {
const item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
});
let i = 0;
function socCounter(){
i++;
// Append message
/*
const item = document.createElement('li');
item.textContent = i;
countermsg.appendChild(item);
console.log(i);
*/
// counter
countermsg.innerHTML = i;
socket.emit('socMessage', i);
}
setInterval(socCounter, 1000);
</script>
</html>
socCounter.html
<html>
<head>
<title>
socket test
</title>
</head>
<body>
<form id="socketForm">
<!-- socket message -->
count receiver<br>
<ul id="countmsg"></ul><br>
</form>
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
const messages = document.getElementById('messages');
const countermsg = document.getElementById('countmsg');
const socket = io();
socket.on('socMessage', (msg) => {
countermsg.innerHTML = msg;
});
</script>
</html>