반업주부의 일상 배움사
socket.io :: koa, hapi, fastify 본문
반응형
성능은 Hapi > Koa > Fastify 순.
Koa
import Koa from 'koa';
import Router from 'koa-router';
import { createServer } from 'http';
import { Server } from 'socket.io';
import serve from 'koa-static';
const app = new Koa();
const router = new Router();
router.get('/', async (ctx) => {
ctx.body = 'Hello, world!';
});
const server = createServer(app.callback());
const socketServer = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
socketServer.on('connection', (socket) => {
console.log(`Client ${socket.id} connected`);
socket.emit('message', 'Welcome to the chat!');
socket.on('disconnect', () => {
console.log(`Client ${socket.id} disconnected`);
});
socket.on('message', (message) => {
// console.log(`Received message from ${socket.id}: ${message}`);
socketServer.emit('message', message);
});
});
app.use(serve(__dirname + '/public'));
app.use(router.routes());
app.use(router.allowedMethods());
server.listen(3400, () => {
console.log('Server started on port 3400');
});
Hapi.js
import Hapi from '@hapi/hapi';
import { Server } from 'socket.io';
const init = async () => {
const server = Hapi.server({
port: 3400,
host: 'localhost',
});
const io = new Server(server.listener);
io.on('connection', (socket) => {
console.log(`Client ${socket.id} connected`);
socket.emit('message', 'Welcome to the chat!');
socket.on('disconnect', () => {
console.log(`Client ${socket.id} disconnected`);
});
socket.on('message', (message) => {
// console.log(`Received message from ${socket.id}: ${message}`);
io.emit('message', message);
});
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
Fastify
import fastify from 'fastify';
import fastifySocketIO from 'fastify-socket.io';
const server = fastify();
server.register(fastifySocketIO);
server.get('/', (_request, reply) => {
reply.send({ hello: 'world' });
});
server.ready().then(() => {
const io = server.io;
io.on('connection', (socket) => {
console.log(`Client ${socket.id} connected`);
socket.emit('message', 'Welcome to the chat!');
socket.on('disconnect', () => {
console.log(`Client ${socket.id} disconnected`);
});
socket.on('message', (message) => {
// console.log(`Received message from ${socket.id}: ${message}`);
io.emit('message', message);
});
});
});
const start = async () => {
try {
const port = 3400;
await server.listen({ port: port });
console.log(`Server is running on ${port}`);
} catch (err) {
console.error(err);
process.exit(1);
}
};
start();
반응형
LIST
'IT 인터넷 > Node.js' 카테고리의 다른 글
SELECT ... FOR UPDATE :: MySQL (0) | 2023.06.19 |
---|---|
JS 배열 섞기 (0) | 2023.05.13 |
ChatGPT가 알려주는 Node.js 모범 사례 30선 (목표 100선) :: Best Practices (0) | 2023.02.07 |
[JavaScript] 파라미터가 양의 정수인지 확인 (0) | 2022.09.05 |
[Node.js] Cannot find module '../build/Release/sharp-darwin-arm64v8.node' (0) | 2022.09.05 |
Comments