提交 | 用户 | age
|
a96cb2
|
1 |
import Koa from 'koa'; |
V |
2 |
import path from 'path'; |
|
3 |
import Router from 'koa-router'; |
|
4 |
import body from 'koa-body'; |
|
5 |
import cors from 'koa2-cors'; |
|
6 |
import koaStatic from 'koa-static'; |
|
7 |
import websockify from 'koa-websocket'; |
|
8 |
import route from 'koa-route'; |
|
9 |
|
|
10 |
import AppRoutes from './routes'; |
|
11 |
|
|
12 |
const PORT = 3300; |
|
13 |
|
|
14 |
const app = websockify(new Koa()); |
|
15 |
|
|
16 |
app.ws.use(function (ctx, next) { |
|
17 |
ctx.websocket.send('connection succeeded!'); |
|
18 |
return next(ctx); |
|
19 |
}); |
|
20 |
|
|
21 |
app.ws.use( |
|
22 |
route.all('/test', function (ctx) { |
|
23 |
// ctx.websocket.send('Hello World'); |
|
24 |
ctx.websocket.on('message', function (message) { |
|
25 |
// do something with the message from client |
|
26 |
|
|
27 |
if (message !== 'ping') { |
|
28 |
const data = JSON.stringify({ |
|
29 |
id: Math.ceil(Math.random() * 1000), |
|
30 |
time: new Date().getTime(), |
|
31 |
res: `${message}`, |
|
32 |
}); |
|
33 |
ctx.websocket.send(data); |
|
34 |
} |
|
35 |
console.log(message); |
|
36 |
}); |
56a966
|
37 |
}), |
a96cb2
|
38 |
); |
V |
39 |
|
|
40 |
const router = new Router(); |
|
41 |
|
|
42 |
// router |
|
43 |
AppRoutes.forEach((route) => router[route.method](route.path, route.action)); |
|
44 |
|
|
45 |
app.use(cors()); |
|
46 |
app.use( |
|
47 |
body({ |
|
48 |
encoding: 'gzip', |
|
49 |
multipart: true, |
|
50 |
formidable: { |
|
51 |
// uploadDir: path.join(__dirname, '/upload/'), // 设置文件上传目录 |
|
52 |
keepExtensions: true, |
|
53 |
maxFieldsSize: 20 * 1024 * 1024, |
|
54 |
}, |
56a966
|
55 |
}), |
a96cb2
|
56 |
); |
V |
57 |
app.use(router.routes()); |
|
58 |
app.use(router.allowedMethods()); |
|
59 |
app.use(koaStatic(path.join(__dirname))); |
|
60 |
|
|
61 |
app.listen(PORT, () => { |
|
62 |
console.log(`Application started successfully: http://localhost:${PORT}`); |
|
63 |
}); |