File tree Expand file tree Collapse file tree 3 files changed +97
-0
lines changed Expand file tree Collapse file tree 3 files changed +97
-0
lines changed Original file line number Diff line number Diff line change
1
+ const app = require ( 'express' ) ( )
2
+ const bodyParser = require ( 'body-parser' )
3
+ const server = require ( 'http' ) . Server ( app )
4
+ const io = require ( 'socket.io' ) ( server )
5
+
6
+ app . use ( bodyParser . urlencoded ( { extended : true } ) ) ;
7
+ app . use ( bodyParser . json ( ) ) ;
8
+ server . listen ( 80 , ( ) => {
9
+ console . log ( 'server listen port = 80' )
10
+ } )
11
+
12
+
13
+
14
+ let ssids = [ ]
15
+ io . on ( 'connection' , socket => {
16
+
17
+ ssids . push ( socket . id )
18
+ socket . emit ( 'news' , { hello :"world" } )
19
+
20
+ socket . on ( 'my other event' , ( data ) => {
21
+ console . log ( data )
22
+ } )
23
+
24
+ setInterval ( ( ) => {
25
+ socket . emit ( 'all' , {
26
+ name :'服务端时间' ,
27
+ time :new Date ( ) ,
28
+ ssids :ssids
29
+ } )
30
+ } , 2000 )
31
+
32
+ // 循环广播
33
+ setInterval ( ( ) => {
34
+ for ( let item of ssids ) {
35
+ // todo 广播如果失败呢
36
+ socket . broadcast . to ( item ) . emit ( 'hi' , { target :item , title :'广播' } )
37
+ }
38
+ } , 10000 )
39
+ } )
40
+
41
+ app . get ( '/' , ( req , res ) => {
42
+ const query = req . query ;
43
+ console . log ( query )
44
+
45
+ io . sockets . emit ( 'send-a' , { target :'通缉A' } )
46
+
47
+ res . sendFile ( __dirname + '/index.html' )
48
+ } )
Original file line number Diff line number Diff line change
1
+ <!DOCTYPE html>
2
+ < html lang ="en ">
3
+ < head >
4
+ < meta charset ="UTF-8 ">
5
+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
6
+ < meta http-equiv ="X-UA-Compatible " content ="ie=edge ">
7
+ < title > Document</ title >
8
+ < script src ="/socket.io/socket.io.js "> </ script >
9
+ < script >
10
+ const socket = io . connect ( 'http://localhost' )
11
+ socket . on ( 'connect' , ( ) => {
12
+ console . log ( '连接socket 服务端成功' )
13
+ } )
14
+ socket . on ( 'news' , ( data ) => {
15
+ console . log ( data )
16
+ } )
17
+
18
+ socket . on ( 'all' , ( data ) => {
19
+ console . log ( data )
20
+ } )
21
+
22
+ socket . on ( 'send-a' , ( data ) => {
23
+ console . log ( 'send-a:' , data )
24
+ } )
25
+
26
+ socket . on ( 'hi' , ( data ) => {
27
+ console . log ( '接受广播:' , data )
28
+ } )
29
+
30
+ setInterval ( ( ) => {
31
+ socket . emit ( 'my other event' , "客户端时间:" + new Date ( ) )
32
+ } , 5000 )
33
+
34
+ </ script >
35
+ </ head >
36
+ < body >
37
+
38
+ </ body >
39
+ </ html >
Original file line number Diff line number Diff line change
1
+ {
2
+ "scripts" : {
3
+ "dev" : " nodemon --inspect app.js 99"
4
+ },
5
+ "dependencies" : {
6
+ "body-parser" : " ^1.19.0" ,
7
+ "express" : " ^4.17.1" ,
8
+ "socket.io" : " ^2.2.0"
9
+ }
10
+ }
You can’t perform that action at this time.
0 commit comments