Created
May 22, 2018 00:30
-
-
Save acdcjunior/45ee38aaf11baed34b33d2aae29c827d to your computer and use it in GitHub Desktop.
websocket express server client example
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
| const WebSocket = require('ws'); | |
| const ws = new WebSocket('ws://localhost:3000/'); | |
| ws.on('open', function open() { | |
| ws.send('sent by client'); | |
| }); | |
| ws.on('message', function incoming(data) { | |
| console.log('received @client', data); | |
| }); |
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
| npm i express express-ws ws |
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
| var express = require('express'); | |
| var app = express(); | |
| var expressWs = require('express-ws')(app); | |
| app.use(function (req, res, next) { | |
| console.log('middleware'); | |
| req.testing = 'testing'; | |
| return next(); | |
| }); | |
| app.get('/', function(req, res, next){ | |
| console.log('get route', req.testing); | |
| res.end(); | |
| }); | |
| app.ws('/', function(ws, req) { | |
| ws.on('message', function(msg) { | |
| console.log('received @server', msg); | |
| ws.send('sent by server'); | |
| }); | |
| console.log('socket', req.testing); | |
| }); | |
| app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment