Created
March 1, 2019 15:42
-
-
Save fabiobusnello/6659618d1873cfa85bf4088eca946920 to your computer and use it in GitHub Desktop.
express web socket server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
não se esqueça de instalar o nodemon globalmente mas nada te impede de instala-local :) | |
$ npm i --save express express-ws | |
$ nodemon app | |
*/ | |
const express = require('express') | |
const expressWs = require('express-ws') | |
const http = require('http') | |
const app = express() | |
const port = '3000' | |
app.server = http.createServer(app) | |
expressWs(app, app.server) | |
//verbos http simples, o mesmo para app.post, app.delete e app.put | |
app.get('*', (req, res, next)=>{ | |
res.json({status: true, message: 'Success'}) | |
}) | |
//aqui é que vc recebe seu socket client | |
app.ws('/:token', (ws, req, next)=>{ | |
const token = req.params.token //ou const {token} = req.params e faça sua validação | |
ws.send('olá, vc está conectado') | |
ws.on('message', data=>console.log(data)) // quando um client envia uma mensagem vc pega ela aqui. | |
ws.on('close', close=>console.log(close)) //fiz assim pra vc entender quando o client desconecta | |
ws.on('error', err=>console.log(err)) | |
}) | |
app.server.listen(port, ()=>{ | |
console.log(`Server running in port ${port}`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment