- vừa được xem lúc

Bước đầu tìm hiểu về Nodejs với Socket

0 0 29

Người đăng: Nguyen Quang Huy

Theo Viblo Asia

Khởi tạo Node Js

Một dự án chạy bằng Node là có Express js. Qua bài https://expressjs.com/en/starter/generator.html thì chúng ta có thể tự động sinh ra cấu trúc dự án giống như trong cấu trúc sau:

.
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views ├── error.pug ├── index.pug └── layout.pug

Sau đó để chạy được dự án thì dựa vào file package.json thì để chạy cần dùng lệnh npm run start

Tích hợp socket io

Để cài đặt thì cần thêm thư viện Socket Io thì dùng lệnh trực tiếp là npm install socket.io tiếp đến để viết riêng 1 phần xử lý riêng phần socket ở trong file bin/www như sau

const io = require('socket.io')(3001, { cors: { origin: 'http://localhost:8000', methods: ["GET", "POST"] }
});
app.set('socketIO', io);
require('../app/controllers/socket')(io);

Khi khai báo như thế này thì sẽ là tạo ra port 3001 để dành cho socket và chỉ nhận request từ đường link http://localhost:8000 Và để có thể config được thông tin này thì có thể dùng env thông qua thư viện dotenv. Như vậy file www sẽ như sau:

#!/usr/bin/env node /** * Module dependencies. */ var app = require('../app');
var debug = require('debug')('chatnodejs:server');
var http = require('http');
require('dotenv').config(); /** * Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || '3000');
var socketPort = normalizePort(process.env.SOCKETPORT || '3001');
var webUrl = process.env.WEBURL || 'http://localhost:8000';
app.set('port', port);
app.set('socketPort', socketPort);
app.set('webUrl', webUrl); /** * Create HTTP server. */ var server = http.createServer(app); /** * Socket IO */
const io = require('socket.io')(socketPort, { cors: { origin: webUrl, methods: ["GET", "POST"] }
});
app.set('socketIO', io);
require('../app/controllers/socket')(io); /** * Listen on provided port, on all network interfaces. */ server.listen(port);
server.on('error', onError);
server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false;
} /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; }
} /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind);
}

Còn về file xử lý socket riêng viết như sau:

module.exports = function(io) { io.on('connection', socket => { socket.on('disconnect', async function() { });
} 

Phần tiếp theo sẽ làm về phía client để làm sự kiện connect, chat message

Bình luận

Bài viết tương tự

- vừa được xem lúc

Cách mình "hack" được vào hẹ thống của SMAS để xem điểm.

Cách mà mình "hack" được vào hệ thống của SMAS. Thật ra dùng từ hack cũng không đúng lắm, chỉ là một vài trick để lừa hệ thống mà thôi.

0 0 124

- vừa được xem lúc

[NodeJs] Tạo QR Code trong nodeJs với qrcode

Tạo mã QR Code trong nodejs với qrcode. QR Code là gì. Tạo QR code với qrcode. Cài đặt thư viện qrcode.

0 0 21

- vừa được xem lúc

Áp dụng kiến trúc 3 Layer Architecture vào project NodeJS

The problem encountered. Các framework nodejs phổ biết như Express cho phép chúng ta dễ dàng tạo ra Resful API xử lí các request từ phía client một cách nhanh chóng và linh hoạt.

0 0 64

- vừa được xem lúc

Router, Controller trong Express

Mở đầu. Xin chào các bạn mình đã quay trở lại rồi đây, tiếp tục với series Nodejs cơ bản thì hôm nay mình sẽ giới thiệu đến các bạn Express Router và Controller.

0 0 30

- vừa được xem lúc

Xây dựng CRUD RESTful API sử dụng Node, Express, MongoDB.

Introduction. Trong phạm vi bài viết này chúng ta sẽ cùng tìm hiểu về cách tạo restful api với Node, Express và MongoDB. . Xử lý các hoạt động crud.

0 0 213

- vừa được xem lúc

Rate time limit trong NodeJS

Chào các bạn, lại là mình đây. Hôm nay mình xin giới thiệu tới các bạn một kỹ thuật rất hay ho và hữu ích đó là Rate Limiting. 1. Rate Limiting là gì.

0 0 48