Преглед изворни кода

Use specific rooms for socket-io

sbkwgh пре 8 година
родитељ
комит
c8b2950bbb
3 измењених фајлова са 14 додато и 2 уклоњено
  1. 10 0
      lib/sockets.js
  2. 1 1
      routes/thread.js
  3. 3 1
      test/socket_io.js

+ 10 - 0
lib/sockets.js

@@ -2,6 +2,16 @@ module.exports = {
 	init (app, server) {
 		let io = require('socket.io')(server)
 
+		io.on('connection', socket => {
+			socket.on('join', room => {
+				socket.join(room)
+			})
+
+			socket.on('leave', room => {
+				socket.leave(room)
+			})
+		})
+
 		app.set('io', io)
 	}
 }

+ 1 - 1
routes/thread.js

@@ -134,7 +134,7 @@ router.post('/', async (req, res) => {
 			]
 		}))
 
-		req.app.get('io').emit('new thread', {
+		req.app.get('io').to('index').emit('new thread', {
 			name: category.name,
 			value: category.value
 		})

+ 3 - 1
test/socket_io.js

@@ -60,8 +60,10 @@ describe('Socket-io', () => {
 
 		it('should emit a notification when a thread is created	', (done) => {
 			let client = io.connect('http://localhost:3000')
+			client.emit('join', 'index')
+
 			client.on('new thread', data => {
-				data.should.have.property('category', 'category_name')
+				data.should.have.property('name', 'category_name')
 
 				done()
 			})