fcs
2025-04-10 0163870d662dc5b7d69ceff977490ede594f7d82
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
 
const fs = require( 'fs' )
const path = require( 'path' )
 
const Koa = require( 'koa' )
const IO = require( '../' )
const co = require( 'co' )
 
const app = new Koa()
const io = new IO()
const chat = new IO( 'chat' )
 
io.attach( app )
chat.attach( app )
 
/**
 * Koa Middlewares
 */
app.use( co.wrap( function *( ctx, next ) {
  const start = new Date
  yield next()
  const ms = new Date - start
  console.log( `${ ctx.method } ${ ctx.url } - ${ ms }ms` )
}))
 
 
/**
 * App handlers
 */
app.use( ctx => {
  ctx.type = 'text/html'
  ctx.body = fs.createReadStream( path.join( __dirname, 'index.html' ) )
})
 
/**
 * Socket middlewares
 */
io.use( co.wrap( function *( ctx, next ) {
  console.log( 'Socket middleware' )
  const start = new Date
  yield next()
  const ms = new Date - start
  console.log( `WS ${ ms }ms` )
}))
io.use( co.wrap( function *( ctx, next ) {
  ctx.teststring = 'test'
  yield next()
}))
 
/**
 * Socket handlers
 */
io.on( 'connection', ctx => {
  console.log( 'Join event', ctx.socket.id )
  io.broadcast( 'connections', {
    numConnections: io.connections.size
  })
  // app.io.broadcast( 'connections', {
  //   numConnections: socket.connections.size
  // })
})
 
io.on( 'disconnect', ctx => {
  console.log( 'leave event', ctx.socket.id )
  io.broadcast( 'connections', {
    numConnections: io.connections.size
  })
})
io.on( 'data', ( ctx, data ) => {
  console.log( 'data event', data )
  console.log( 'ctx:', ctx.event, ctx.data, ctx.socket.id )
  console.log( 'ctx.teststring:', ctx.teststring )
  ctx.socket.emit( 'response', {
    message: 'response from server'
  })
})
io.on( 'ack', ( ctx, data ) => {
  console.log( 'data event with acknowledgement', data )
  ctx.acknowledge( 'received' )
})
io.on( 'numConnections', packet => {
  console.log( `Number of connections: ${ io.connections.size }` )
})
 
/**
 * Chat handlers
 */
chat.on( 'connection', ctx => {
  console.log( 'Joining chat namespace', ctx.socket.id )
})
chat.on( 'message', ctx => {
  console.log( 'chat message received', ctx.data )
 
  // Broadcasts to everybody, including this connection
  app.chat.broadcast( 'message', 'yo connections, lets chat' )
 
  // Broadcasts to all other connections
  ctx.socket.broadcast( 'message', 'ok connections:chat:broadcast' )
 
  // Emits to just this socket
  ctx.socket.emit( 'message', 'ok connections:chat:emit' )
})
 
const PORT = 3000
app.listen( 3000, () => {
  console.log( `Listening on ${ PORT }` )
} )