Socket.io 의 공식 문서의 예제(Example) 를 따라 정리하다 보니 Node.js 기반으로 작성되어 있기에 자연스럽게 접하게 되었다.
Node.js 가 Javascript 기반이라고는 하나 메서드나 외부 모듈을 가져오는 방법 등이 다르고, React 에 익숙해져있는 상태이기에 이번 기회를 통해 새로 알게 된 지식을 정리하는 것이 좋겠다.
Node.js 의 프레임워크인 Express 환경에서 작성한다.
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
<string>
현재 모듈의 디렉토리 이름이다. __filename 의 path.dirname() 와 같다.
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
// Importing a local module with a path relative to the `__dirname` or current
// working directory. (On Windows, this would resolve to .\path\myLocalModule.)
const myLocalModule = require('./path/myLocalModule');
// Importing a JSON file:
const jsonData = require('./path/filename.json');
// Importing a module from node_modules or Node.js built-in module:
const crypto = require('node:crypto');
id
<string>
module name or path<any>
exported module content모듈, JSON 및 로컬 파일을 가져오는 데 사용된다. 모듈은 node_modules
로 부터 가져올 수 있다. 로컬 모듈 및 JSON 파일은 __dirname(정의된 경우) 혹은 현재 작업 중인 디렉터리로 명명된 디렉터리에 대해 제공되어질 상대 경로(예: ./
, ./foo
, ./bar/baz
, ../foo
)를 사용하여 가져올 수 있다.
io.on("connection", (socket) => {
console.log("a user connected");
});
eventName
<string> | <symbol>
The name of the event.listener
<Function>
The callback function<EventEmitter>
eventName
이라는 이벤트에 대한 리스너 배열의 끝에 listener
함수를 추가한다. listener
가 이미 추가되었는지 확인하기 위한 검사는 수행되지 않는다. 같은 eventName
과 listener
조합을 전달하는 다중 호출은 리스너가 여러 번 추가되고 호출되는 결과를 만든다.
server.on('connection', (stream) => {
console.log('someone connected!');
});
호출을 연결할 수 있도록 EventEmitter
에 대한 참조를 반환한다.
기본적으로 이벤트 리스너는 추가된 순서대로 호출된다. emitter.prependListener()
메서드는 이벤트 리스너를 리스너 배열의 시작 부분에 추가하기 위한 대안으로 사용할 수 있다.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
const EventEmitter = require('node:events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
eventName
<string> | <symbol>
<any>
<boolean>
eventName
이라는 이벤트에 대해 등록된 각 리스너를 등록된 순서대로 동기식으로 호출하고 제공된 인수를 각각에 전달한다.
만약 이벤트에 리스너가 있다면 true
를 반환하고, 아니면 false
를 반환한다.
+ Broadcasting
broadcasting 은 오직 서버에서만 제공되는 기능 임을 유념해야한다.
io.emit("hello", "world");
io.on("connection", (socket) => {
socket.broadcast.emit("hello", "world");
});