域名购买完成后, 须要将域名解析到实验云主机上node
# ping wx.abcgogo.com -c 4 PING wx.abcgogo.com (203.195.219.131) 56(84) bytes of data. 64 bytes from 203.195.219.131: icmp_seq=1 ttl=63 time=3.48 ms 64 bytes from 203.195.219.131: icmp_seq=2 ttl=63 time=3.42 ms 64 bytes from 203.195.219.131: icmp_seq=3 ttl=63 time=3.44 ms 64 bytes from 203.195.219.131: icmp_seq=4 ttl=63 time=3.43 ms --- wx.abcgogo.com ping statistics --- 4 packets transmitted, 4 received, 0% packet loss, time 3002ms rtt min/avg/max/mdev = 3.421/3.445/3.488/0.048 ms
若是你还不是小程序开发者,请先在微信公众平台并注册:linux
配置小程序服务器信息c++
登陆微信公众平台后,依次进入 设置
- 开发设置
- 服务器域名
- 修改
。git
扫码完成身份校验后,request 合法域名和 socket 合法域名均填写在上一步准备好的域名地址。web
配置完成后,点击 保存并提交
。您能够点击以下视频查看如何进行配置:mongodb
要运行本实验配套的小程序代码,请下载下列资源:docker
下载后,请解压到本地工做目录。shell
开发工具下载后,请安装并启动,而后用微信扫码登陆。express
登陆后,选择 本地小程序项目
- 添加项目
,使用如下配置:
设置
- 开发设置
- 开发者 ID
中查看app.js
)填写完成后,点击 添加项目
设置实验域名
在开发工具的 编辑
面板中,选中 app.js
进行编辑,须要修改小程序通讯域名
,请参考下面的配置:
App({ config: { host: '' // 这个地方填写你的域名 }, onLaunch () { console.log('App.onLaunch()'); } });
下面的步骤,将带你们在服务器上使用 Node 和 Express 搭建一个 HTTP 服务器
安装 NodeJS 和 NPM
使用下面的命令安装 NodeJS 和 NPM
curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash - yum install nodejs -y
安装完成后,使用下面的命令测试安装结果
node -v
[root@VM_144_54_centos ~]# curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash - ## Installing the NodeSource Node.js 8.x LTS Carbon repo... ## Inspecting system... + rpm -q --whatprovides redhat-release || rpm -q --whatprovides centos-release || rpm -q --whatprovides cloudlinux-release || rpm -q --whatprovides sl-release + uname -m ## Confirming "el7-x86_64" is supported... + curl -sLf -o /dev/null 'https://rpm.nodesource.com/pub_8.x/el/7/x86_64/nodesource-release-el7-1.noarch.rpm' ## Downloading release setup RPM... + mktemp + curl -sL -o '/tmp/tmp.rZERimI62Z' 'https://rpm.nodesource.com/pub_8.x/el/7/x86_64/nodesource-release-el7-1.noarch.rpm' ## Installing release setup RPM... + rpm -i --nosignature --force '/tmp/tmp.rZERimI62Z' ## Cleaning up... + rm -f '/tmp/tmp.rZERimI62Z' ## Checking for existing installations... + rpm -qa 'node|npm' | grep -v nodesource ## Run `sudo yum install -y nodejs` to install Node.js 8.x LTS Carbon and npm. ## You may also need development tools to build native addons: sudo yum install gcc-c++ make ## To install the Yarn package manager, run: curl -sL https://dl.yarnpkg.com/rpm/yarn.repo | sudo tee /etc/yum.repos.d/yarn.repo sudo yum install yarn [root@VM_144_54_centos ~]# yum install nodejs -y Loaded plugins: fastestmirror, langpacks epel | 4.7 kB 00:00 extras | 3.4 kB 00:00 nodesource | 2.5 kB 00:00 os | 3.6 kB 00:00 updates | 3.4 kB 00:00 (1/8): epel/7/x86_64/group_gz | 88 kB 00:00 (2/8): epel/7/x86_64/updateinfo | 1.0 MB 00:00 (3/8): os/7/x86_64/group_gz | 166 kB 00:00 (4/8): extras/7/x86_64/primary_db | 187 kB 00:00 (5/8): os/7/x86_64/primary_db | 6.0 MB 00:00 (6/8): epel/7/x86_64/primary_db | 6.6 MB 00:00 (7/8): updates/7/x86_64/primary_db | 3.4 MB 00:00 (8/8): nodesource/x86_64/primary_db | 45 kB 00:00 Determining fastest mirrors Resolving Dependencies --> Running transaction check ---> Package nodejs.x86_64 2:8.15.1-1nodesource will be installed --> Finished Dependency Resolution Dependencies Resolved =============================================================================== Package Arch Version Repository Size =============================================================================== Installing: nodejs x86_64 2:8.15.1-1nodesource nodesource 16 M Transaction Summary =============================================================================== Install 1 Package Total download size: 16 M Installed size: 49 M Downloading packages: warning: /var/cache/yum/x86_64/7/nodesource/packages/nodejs-8.15.1-1nodesource.x86_64.rpm: Header V4 RSA/SHA512 Signature, key ID 34fa74dd: NOKEY Public key for nodejs-8.15.1-1nodesource.x86_64.rpm is not installed nodejs-8.15.1-1nodesource.x86_64.rpm | 16 MB 00:01 Retrieving key from file:///etc/pki/rpm-gpg/NODESOURCE-GPG-SIGNING-KEY-EL Importing GPG key 0x34FA74DD: Userid : "NodeSource <gpg-rpm@nodesource.com>" Fingerprint: 2e55 207a 95d9 944b 0cc9 3261 5ddb e8d4 34fa 74dd Package : nodesource-release-el7-1.noarch (installed) From : /etc/pki/rpm-gpg/NODESOURCE-GPG-SIGNING-KEY-EL Running transaction check Running transaction test Transaction test succeeded Running transaction Warning: RPMDB altered outside of yum. Installing : 2:nodejs-8.15.1-1nodesource.x86_64 1/1 Verifying : 2:nodejs-8.15.1-1nodesource.x86_64 1/1 Installed: nodejs.x86_64 2:8.15.1-1nodesource Complete! [root@VM_144_54_centos ~]# node -v v8.15.1
编写 HTTP Server 源码
使用下面的命令在服务器建立一个工做目录:
mkdir -p /data/release/weapp
进入此工做目录
cd /data/release/weapp
在刚才建立的工做目录建立 package.json,添加咱们服务器包的名称和版本号,可参考下面的示例。
package.json { "name": "weapp", "version": "1.0.0" }
完成后 保存文件
在工做目录建立 app.js,使用 Express.js 来监听 8765
端口,可参考下面的示例代码。
app.js
// 引用 express 来支持 HTTP Server 的实现 const express = require('express'); // 建立一个 express 实例 const app = express(); // 实现惟一的一个中间件,对于全部请求,都输出 "Response from express" app.use((request, response, next) => { response.write('Response from express'); response.end(); }) // 监听端口,等待链接 const port = 8765; app.listen(port); // 输出服务器启动日志 console.log(`Server listening at http://127.0.0.1:${port}`);
运行 HTTP 服务
在开始以前,咱们先来安装PM2
npm install pm2 --global [root@VM_144_54_centos weapp]# npm install pm2 --global [..................] | fetchMetadata: sill resolveWithNewModule pm2@3.4.1 chec [..................] | fetchMetadata: sill resolveWithNewModule pm2@3.4.1 chec [..................] | fetchMetadata: sill resolveWithNewModule pm2@3.4.1 chec [..................] | fetchMetadata: sill resolveWithNewModule pm2@3.4.1 chec [..................] | fetchMetadata: sill resolveWithNewModule pm2@3.4.1 chec [..................] | fetchMetadata: sill resolveWithNewModule pm2@3.4.1 chec [..................] | fetchMetadata: sill resolveWithNewModule pm2@3.4.1 chec [..................] | fetchMetadata: sill resolveWithNewModule pm2@3.4.1 chec /usr/bin/pm2 -> /usr/lib/node_modules/pm2/bin/pm2 /usr/bin/pm2-dev -> /usr/lib/node_modules/pm2/bin/pm2-dev /usr/bin/pm2-docker -> /usr/lib/node_modules/pm2/bin/pm2-docker /usr/bin/pm2-runtime -> /usr/lib/node_modules/pm2/bin/pm2-runtime npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.7 (node_modules/pm2/node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.7: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
PM2 安装时间可能稍长,请耐心等候
咱们的服务器源码里使用到了 Express 模块,下面的命令使用 NPM 来安装 Express
cd /data/release/weapp npm install express --save # npm install express --save npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN weapp@1.0.0 No description npm WARN weapp@1.0.0 No repository field. npm WARN weapp@1.0.0 No license field. + express@4.16.4 added 48 packages from 36 contributors and audited 121 packages in 11.182s found 0 vulnerabilities
安装完成后,使用 PM2 来启动 HTTP 服务
cd /data/release/weapp pm2 start app.js
如今,您的 HTTP 服务已经在 http://203.195.219.131:8765运行
要查看服务输出的日志,可使用下面的命令:
pm2 logs
若是要重启服务,可使用下面的命令:
pm2 restart app
pm2 restart app Use --update-env to update environment variables [PM2] Applying action restartProcessId on app [app](ids: 0) [PM2] [app](0) ✓ ┌──────┬────┬──────┬────────┬───┬─────┬───────────┐ │ Name │ id │ mode │ status │ ↺ │ cpu │ memory │ ├──────┼────┼──────┼────────┼───┼─────┼───────────┤ │ app │ 0 │ fork │ online │ 1 │ 0% │ 10.2 MB │ └──────┴────┴──────┴────────┴───┴─────┴───────────┘ Use `pm2 show <id|name>` to get more details about an app
微信小程序要求和服务器的通讯都经过 HTTPS 进行
在 CentOS 上,可直接使用 yum
来安装 Nginx
yum install nginx -y
安装完成后,使用 nginx
命令启动 Nginx:
nginx
此时,访问 http://203.195.219.131 能够看到 Nginx 的测试页面
外网用户访问服务器的 Web 服务由 Nginx 提供,Nginx 须要配置反向代理才能使得 Web 服务转发到本地的 Node 服务。
先将以前下载的 SSL 证书(解压后 Nginx 目录分别以 crt 和 key 做为后缀的文件)经过拖动到左侧文件浏览器/etc/nginx目录
的方式来上传文件到服务器上
如何上传 SSL 证书到 /etc/nginx 目录
Nginx 配置目录在 /etc/nginx/conf.d,咱们在该目录建立 ssl.conf # ssl 配置
cat /etc/nginx/conf.d/ssl.conf server { listen 443; server_name wx.abcgogo.com; # 改成绑定证书的域名 # ssl 配置 ssl on; ssl_certificate fullchain.pem; # 改成本身申请获得的 crt 文件的名称 ssl_certificate_key privkey.pem; # 改成本身申请获得的 key 文件的名称 ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; ssl_prefer_server_ciphers on; location / { proxy_pass http://127.0.0.1:8765; } }
保存配置文件,让 Nginx 从新加载配置使其生效:
nginx -s reload
curl https://wx.abcgogo.com/ Response from express#
在浏览器经过 https 的方式访问你解析的域名来测试 HTTPS 是否成功启动
在小程序中测试 HTTPS 访问
打开配套的小程序,点击 实验一:HTTPS
,点击 发送请求
来测试访问结果。
若是服务器响应成功,请点击下一步。
小程序不支持 Cookie 存储和跟踪,服务器须要自行实现会话层
安装 MongoDB
使用 Yum 在机器上安MongoDB
及其客户端命令行工具:
yum install mongodb-server mongodb -y
安装结束后,可使用下面的命令查看安装的版本:
mongod --version mongo --version # mongod --version mongo --versiondb version v2.6.12 2019-03-27T20:13:40.412+0800 git version: nogitversion 2019-03-27T20:13:40.412+0800 OpenSSL version: OpenSSL 1.0.2k-fips 26 Jan 2017
建立目录,用于 MongoDB 数据和日志存储:
mkdir -p /data/mongodb mkdir -p /data/logs/mongodb
建立后,使用下面的命令来启动 MongoDB:
mongod --fork --dbpath /data/mongodb --logpath /data/logs/mongodb/weapp.log
可使用下面的命令来检查是否启动成功
netstat -ltp | grep 27017
[root@VM_144_54_centos ~]# mkdir -p /data/mongodb [root@VM_144_54_centos ~]# mkdir -p /data/logs/mongodb [root@VM_144_54_centos ~]# mongod --fork --dbpath /data/mongodb --logpath /data/logs/mongodb/weapp.log about to fork child process, waiting until server is ready for connections. forked process: 21051 child process started successfully, parent exiting [root@VM_144_54_centos ~]# [root@VM_144_54_centos ~]# [root@VM_144_54_centos ~]# netstat -ltp | grep 27017 tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 21051/mongod
登陆本地 MongoDB 服务:
mongo
登陆后,建立一个用户 `weap:
use weapp; db.createUser({ user: 'weapp', pwd: 'weapp-dev', roles: ['dbAdmin', 'readWrite']});
建立完成后,使用 exit
退出命令行工具
[root@VM_144_54_centos ~]# mongo MongoDB shell version: 2.6.12 connecting to: test Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see http://docs.mongodb.org/ Questions? Try the support group http://groups.google.com/group/mongodb-user Server has startup warnings: 2019-03-27T20:15:09.144+0800 [initandlisten] 2019-03-27T20:15:09.144+0800 [initandlisten] ** WARNING: Readahead for /data/mongodb is set to 4096KB 2019-03-27T20:15:09.144+0800 [initandlisten] ** We suggest setting it to 256KB (512 sectors) or less 2019-03-27T20:15:09.144+0800 [initandlisten] ** http://dochub.mongodb.org/core/readahead > use weapp; switched to db weapp > db.createUser({ user: 'weapp', pwd: 'weapp-dev', roles: ['dbAdmin', 'readWrite']}); Successfully added user: { "user" : "weapp", "roles" : [ "dbAdmin", "readWrite" ] } > exit bye
实现小程序的会话功能,咱们须要安装connect-mongo和wafer-node-session
cd /data/release/weapp npm install connect-mongo wafer-node-session --save npm WARN weapp@1.0.0 No description npm WARN weapp@1.0.0 No repository field. npm WARN weapp@1.0.0 No license field. + connect-mongo@2.0.3 + wafer-node-session@1.0.10 added 65 packages from 66 contributors and audited 216 packages in 14.861s found 0 vulnerabilities
实现小程序会话
在工做目录建立配置文件 config.js,用于保存咱们服务所用的配置
,可参考下面的实现(注:请将参考配置文件中的 YORU_APP_ID 和 YOUR_APP_SECRET 替换为你申请的小程序对应的 AppID 和 AppSecret):
# cat !$ cat config.js module.exports = { serverPort: '8765', // 小程序 appId 和 appSecret // 请到 https://mp.weixin.qq.com 获取 AppID 和 AppSecret appId: 'wx230a8ffbace', appSecret: '56a8d8ssc9rt147825d47186b', // mongodb 链接配置,生产环境请使用更复杂的用户名密码 mongoHost: '127.0.0.1', mongoPort: '27017', mongoUser: 'weapp', mongoPass: 'weapp-dev', mongoDb: 'weapp' };
编辑 app.js,添加会话实现逻辑,可参考下面的代码:
cat app.js
// 引用 express 来支持 HTTP Server 的实现 const express = require('express'); // 引用 wafer-session 支持小程序会话 const waferSession = require('wafer-node-session'); // 使用 MongoDB 做为会话的存储 const MongoStore = require('connect-mongo')(waferSession); // 引入配置文件 const config = require('./config'); // 建立一个 express 实例 const app = express(); // 添加会话中间件,登陆地址是 /login app.use(waferSession({ appId: config.appId, appSecret: config.appSecret, loginPath: '/login', store: new MongoStore({ url: `mongodb://${config.mongoUser}:${config.mongoPass}@${config.mongoHost}:${config.mongoPort}/${config.mongoDb}` }) })); // 在路由 /me 下,输出会话里包含的用户信息 app.use('/me', (request, response, next) => { response.json(request.session ? request.session.userInfo : { noBody: true }); if (request.session) { console.log(`Wafer session success with openId=${request.session.userInfo.openId}`); } }); // 实现一个中间件,对于未处理的请求,都输出 "Response from express" app.use((request, response, next) => { response.write('Response from express'); response.end(); }); // 监听端口,等待链接 app.listen(config.serverPort); // 输出服务器启动日志 console.log(`Server listening at http://127.0.0.1:${config.serverPort}`);
源码编写完成后,重启服务:
pm2 restart app
重启后,使用配套的小程序完成会话测试:打开配套小程序 - 点击 实验二:会话
- 获取会话
,若是您能看到您的微信头像,那就表示会话已经成功获取了。
安装 Node 模块
本实验使用 ws
模块来在服务器上支持 WebSocket 协议,下面使用 NPM 来安装:
cd /data/release/weapp npm install ws --save
# npm install ws --save npm WARN weapp@1.0.0 No description npm WARN weapp@1.0.0 No repository field. npm WARN weapp@1.0.0 No license field. + ws@6.2.1 added 2 packages from 2 contributors and audited 218 packages in 3.356s found 0 vulnerabilities
建立 websocket.js,实现 WebSocket 服务,可参考下面的代码:
# vi websocket.js [root@VM_144_54_centos weapp]# cat !$ cat websocket.js // 引入 ws 支持 WebSocket 的实现 const ws = require('ws'); // 导出处理方法 exports.listen = listen; /** * 在 HTTP Server 上处理 WebSocket 请求 * @param {http.Server} server * @param {wafer.SessionMiddleware} sessionMiddleware */ function listen(server, sessionMiddleware) { // 使用 HTTP Server 建立 WebSocket 服务,使用 path 参数指定须要升级为 WebSocket 的路径 const wss = new ws.Server({ server, path: '/ws' }); // 监听 WebSocket 链接创建 wss.on('connection', (ws,request) => {// 要升级到 WebSocket 协议的 HTTP 链接 // 被升级到 WebSocket 的请求不会被 express 处理, // 须要使用会话中间节获取会话 sessionMiddleware(request, null, () => { const session = request.session; if (!session) { // 没有获取到会话,强制断开 WebSocket 链接 ws.send(JSON.stringify(request.sessionError) || "No session avaliable"); ws.close(); return; } // 保留这个日志的输出可以让实验室能检查到当前步骤是否完成 console.log(`WebSocket client connected with openId=${session.userInfo.openId}`); serveMessage(ws, session.userInfo); }); }); // 监听 WebSocket 服务的错误 wss.on('error', (err) => { console.log(err); }); } /** * 进行简单的 WebSocket 服务,对于客户端发来的全部消息都回复回去 */ function serveMessage(ws, userInfo) { // 监听客户端发来的消息 ws.on('message', (message) => { console.log(`WebSocket received: ${message}`); ws.send(`Server: Received(${message})`); }); // 监听关闭事件 ws.on('close', (code, message) => { console.log(`WebSocket client closed (code: ${code}, message: ${message || 'none'})`); }); // 链接后立刻发送 hello 消息给会话对应的用户 ws.send(`Server: 恭喜,${userInfo.nickName}`); }
编辑 app.js,调用 WebSocket 服务,可参考下面代码:
// HTTP 模块同时支持 Express 和 WebSocket const http = require('http'); // 引用 express 来支持 HTTP Server 的实现 const express = require('express'); // 引用 wafer-session 支持小程序会话 const waferSession = require('wafer-node-session'); // 使用 MongoDB 做为会话的存储 const MongoStore = require('connect-mongo')(waferSession); // 引入配置文件 const config = require('./config'); // 引入 WebSocket 服务实现 const websocket = require('./websocket'); // 建立一个 express 实例 const app = express(); // 独立出会话中间件给 express 和 ws 使用 const sessionMiddleware = waferSession({ appId: config.appId, appSecret: config.appSecret, loginPath: '/login', store: new MongoStore({ url: `mongodb://${config.mongoUser}:${config.mongoPass}@${config.mongoHost}:${config.mongoPort}/${config.mongoDb}` }) }); app.use(sessionMiddleware); // 在路由 /me 下,输出会话里包含的用户信息 app.use('/me', (request, response, next) => { response.json(request.session ? request.session.userInfo : { noBody: true }); if (request.session) { console.log(`Wafer session success with openId=${request.session.userInfo.openId}`); } }); // 实现一个中间件,对于未处理的请求,都输出 "Response from express" app.use((request, response, next) => { response.write('Response from express'); response.end(); }); // 建立 HTTP Server 而不是直接使用 express 监听 const server = http.createServer(app); // 让 WebSocket 服务在建立的 HTTP 服务器上监听 websocket.listen(server, sessionMiddleware); // 启动 HTTP 服务 server.listen(config.serverPort); // 输出服务器启动日志 console.log(`Server listening at http://127.0.0.1:${config.serverPort}`);
修改完成后 保存文件,并重启服务:
pm2 restart app # pm2 restart app Use --update-env to update environment variables [PM2] Applying action restartProcessId on app [app](ids: 0) [PM2] [app](0) ✓ ┌──────────┬────┬─────────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────┬──────────┐ │ App name │ id │ version │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │ ├──────────┼────┼─────────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────┼──────────┤ │ app │ 0 │ 1.0.0 │ fork │ 31561 │ online │ 3 │ 0s │ 0% │ 10.2 MB │ root │ disabled │ └──────────┴────┴─────────┴──────┴───────┴────────┴─────────┴────────┴─────┴───────────┴──────┴──────────┘ Use `pm2 show <id|name>` to get more details about an app
编辑 Nginx 配置 ssl.conf,添加 WebSocket 支持,可参考下面的配置(注:请将参考配置文件中的 www.example.com 替换为前面步骤申请的域名,将 1_www.example.com.crt 和 2_www.example.com.key 替换为前面步骤申请并上传的 SSL 证书的名称):
[root@VM_144_54_centos weapp]# cat !$ cat /etc/nginx/conf.d/ssl.conf # WebSocket 配置 map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 443; server_name wx.abcgogo.com; # 改成绑定证书的域名 # ssl 配置 ssl on; ssl_certificate fullchain.pem; # 改成本身申请获得的 crt 文件的名称 ssl_certificate_key privkey.pem; # 改成本身申请获得的 key 文件的名称 ssl_session_timeout 5m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; ssl_prefer_server_ciphers on; # WebSocket 配置 proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; location / { proxy_pass http://127.0.0.1:8765; } }
nginx -s reload
建立 /data/release/weapp/game 目录用于存放剪刀石头布小游戏的代码
mkdir -p /data/release/weapp/game
添加 game/Room.js 实现游戏房间逻辑,可参考下面的代码:
/** enum GameChoice { // 剪刀 Scissors = 1, // 石头 Rock = 2, // 布 Paper = 3 } */ function judge(choice1, choice2) { // 和局 if (choice1 == choice2) return 0; // Player 1 没出,Player 2 胜出 if (!choice1) return 1; // Player 2 没出,Player 1 胜出 if (!choice2) return -1; // 都出了就这么算 return (choice1 - choice2 + 3) % 3 == 1 ? -1 : 1; } /** @type {Room[]} */ const globalRoomList = []; // 每一个房间最多两人 const MAX_ROOT_MEMBER = 2; // 游戏时间,单位秒 const GAME_TIME = 3; let nextRoomId = 0; /** 表示一个房间 */ module.exports = class Room { /** 获取全部房间 */ static all() { return globalRoomList.slice(); } /** 获取有座位的房间 */ static findRoomWithSeat() { return globalRoomList.find(x => !x.isFull()); } /** 建立新房间 */ static create() { const room = new Room(); globalRoomList.unshift(room); return room; } constructor() { this.id = `room${nextRoomId++}`; this.players = []; } /** 添加玩家 */ addPlayer(player) { const { uid, uname } = player.user; console.log(`Player ${uid}(${uname}) enter ${this.id}`); this.players.push(player); if (this.isFull()) { this.startGame(); } } /** 删除玩家 */ removePlayer(player) { const { uid, uname } = player.user; console.log(`Player ${uid}(${uname}) leave ${this.id}`); const playerIndex = this.players.indexOf(player); if (playerIndex != -1) { this.players.splice(playerIndex, 1); } if (this.players.length === 0) { console.log(`Room ${this.id} is empty now`); const roomIndex = globalRoomList.indexOf(this); if (roomIndex > -1) { globalRoomList.splice(roomIndex, 1); } } } /** 玩家已满 */ isFull() { return this.players.length == MAX_ROOT_MEMBER; } /** 开始游戏 */ startGame() { // 保留这行日志输出可让实验室检查到实验的完成状况 console.log('game started!'); // 当局积分清零 this.players.forEach(player => player.gameData.roundScore = 0); // 集合玩家用户和游戏数据 const players = this.players.map(player => Object.assign({}, player.user, player.gameData)); // 通知全部玩家开始 for (let player of this.players) { player.send('start', { gameTime: GAME_TIME, players }); } // 计时结束 setTimeout(() => this.finishGame(), GAME_TIME * 1000); } /** 结束游戏 */ finishGame() { const players = this.players; // 两两对比算分 for (let i = 0; i < MAX_ROOT_MEMBER; i++) { let p1 = players[i]; if (!p1) break; for (let j = i + 1; j < MAX_ROOT_MEMBER; j++) { let p2 = players[j]; const result = judge(p1.gameData.choice, p2.gameData.choice); p1.gameData.roundScore -= result; p2.gameData.roundScore += result; } } // 计算连胜奖励 for (let player of players) { const gameData = player.gameData; // 胜局积分 if (gameData.roundScore > 0) { gameData.winStreak++; gameData.roundScore *= gameData.winStreak; } // 败局清零 else if (gameData.roundScore < 0) { gameData.roundScore = 0; gameData.winStreak = 0; } // 累积总分 gameData.totalScore += gameData.roundScore; } // 计算结果 const result = players.map(player => { const { uid } = player.user; const { roundScore, totalScore, winStreak, choice } = player.gameData; return { uid, roundScore, totalScore, winStreak, choice }; }); // 通知全部玩家游戏结果 for (let player of players) { player.send('result', { result }); } } }
实现玩家逻辑
添加 game/Player.js 实现玩家逻辑,可参考下面的代码:
const Room = require("./Room"); /** * 表示一个玩家,处理玩家的公共游戏逻辑,消息处理部分须要具体的玩家实现(请参考 ComputerPlayer 和 HumanPlayer) */ module.exports = class Player { constructor(user) { this.id = user.uid; this.user = user; this.room = null; this.gameData = { // 当前的选择(剪刀/石头/布) choice: null, // 局积分 roundScore: 0, // 总积分 totalScore: 0, // 连胜次数 winStreak: 0 }; } /** * 上线当前玩家,而且异步返回给玩家分配的房间 */ online(room) { // 处理玩家 'join' 消息 // 为玩家寻找一个可用的房间,而且异步返回 this.receive('join', () => { if (this.room) { this.room.removePlayer(this); } room = this.room = room || Room.findRoomWithSeat() || Room.create(); room.addPlayer(this); }); // 处理玩家 'choise' 消息 // 须要记录玩家当前的选择,而且通知到房间里的其它玩家 this.receive('choice', ({ choice }) => { this.gameData.choice = choice; this.broadcast('movement', { uid: this.user.uid, movement: "choice" }); }); // 处理玩家 'leave' 消息 // 让玩家下线 this.receive('leave', () => this.offline); } /** * 下线当前玩家,从房间离开 */ offline() { if (this.room) { this.room.removePlayer(this); this.room = null; } this.user = null; this.gameData = null; } /** * 发送指定消息给当前玩家,须要具体子类实现 * @abstract * @param {string} message 消息类型 * @param {*} data 消息数据 */ send(message, data) { throw new Error('Not implement: AbstractPlayer.send()'); } /** * 处理玩家发送的消息,须要具体子类实现 * @abstract * @param {string} message 消息类型 * @param {Function} handler */ receive(message, handler) { throw new Error('Not implement: AbstractPlayer.receive()'); } /** * 给玩家所在房间里的其它玩家发送消息 * @param {string} message 消息类型 * @param {any} data 消息数据 */ broadcast(message, data) { if (!this.room) return; this.others().forEach(neighbor => neighbor.send(message, data)); } /** * 得到玩家所在房间里的其余玩家 */ others() { return this.room.players.filter(player => player != this); } }
在实现人类玩家以前,咱们先来建立 ComputerPlayer.js 来实现电脑玩家
vi ComputerPlayer.js
const EventEmitter = require('events'); const Player = require('./Player'); let nextComputerId = 0; /** * 机器人玩家实现,使用 EventEmitter 接收和发送消息 */ module.exports = class ComputerPlayer extends Player { constructor() { const computerId = `robot-${++nextComputerId}`; super({ uid: computerId, uname: computerId, uavatar: 'http://www.scoutiegirl.com/wp-content/uploads/2015/06/Blue-Robot.png' }); this.emitter = new EventEmitter(); } /** * 模拟玩家行为 */ simulate() { this.receive('start', () => this.play()); this.receive('result', () => this.stop()); this.send('join'); } /** * 游戏开始后,随机时间后随机选择 */ play() { this.playing = true; const randomTime = () => Math.floor(100 + Math.random() * 2000); const randomChoice = () => { if (!this.playing) return; this.send("choice", { choice: Math.floor(Math.random() * 10000) % 3 + 1 }); setTimeout(randomChoice, randomTime()); } setTimeout(randomChoice, 10); } /** * 游戏结束后,标记起来,阻止继续随机选择 */ stop() { this.playing = false; } /** * 发送消息给当前玩家,直接转发到 emitter */ send(message, data) { this.emitter.emit(message, data); } /** * 从当前的 emitter 处理消息 */ receive(message, handle) { this.emitter.on(message, handle); } }
人类玩家经过 WebSocket 信道来实现玩家的输入输出,咱们须要添加 game/Tunnel.js 和 game/HumanPlayer.js 来实现人类玩家逻辑,可参考下面的代码:
const EventEmitter = require('events'); /** * 封装 WebSocket 信道 */ module.exports = class Tunnel { constructor(ws) { this.emitter = new EventEmitter(); this.ws = ws; ws.on('message', packet => { try { // 约定每一个数据包格式:{ message: 'type', data: any } const { message, data } = JSON.parse(packet); this.emitter.emit(message, data); } catch (err) { console.log('unknown packet: ' + packet); } }); } on(message, handle) { this.emitter.on(message, handle); } emit(message, data) { this.ws.send(JSON.stringify({ message, data })); } }
const co = require('co'); const Player = require('./Player'); const ComputerPlayer = require('./ComputerPlayer'); const Tunnel = require('./Tunnel'); /** * 人类玩家实现,经过 WebSocket 信道接收和发送消息 */ module.exports = class HumanPlayer extends Player { constructor(user, ws) { super(user); this.ws = ws; this.tunnel = new Tunnel(ws); this.send('id', user); } /** * 人类玩家上线后,还须要监听信道关闭,让玩家下线 */ online(room) { super.online(room); this.ws.on('close', () => this.offline()); // 人类玩家请求电脑玩家 this.receive('requestComputer', () => { const room = this.room; while(room && !room.isFull()) { const computer = new ComputerPlayer(); computer.online(room); computer.simulate(); } }); } /** * 下线后关闭信道 */ offline() { super.offline(); if (this.ws && this.ws.readyState == this.ws.OPEN) { this.ws.close(); } this.ws = null; this.tunnel = null; if (this.room) { // 清理房间里面的电脑玩家 for (let player of this.room.players) { if (player instanceof ComputerPlayer) { this.room.removePlayer(player); } } this.room = null; } } /** * 经过 WebSocket 信道发送消息给玩家 */ send(message, data) { this.tunnel.emit(message, data); } /** * 从 WebSocket 信道接收玩家的消息 */ receive(message, callback) { this.tunnel.on(message, callback); } }
游戏的实现已经完成了,接下来,编辑 websocket.js 添加服务入口,可参考下面的代码:
[root@VM_144_54_centos game]# vi ../websocket.js
// 引入 url 模块用于解析 URL const url = require('url'); // 引入 ws 支持 WebSocket 的实现 const ws = require('ws'); // 引入人类玩家 const HumanPlayer = require('./game/HumanPlayer'); // 导出处理方法 exports.listen = listen; /** * 在 HTTP Server 上处理 WebSocket 请求 * @param {http.Server} server * @param {wafer.SessionMiddleware} sessionMiddleware */ function listen(server, sessionMiddleware) { // 使用 HTTP Server 建立 WebSocket 服务,使用 path 参数指定须要升级为 WebSocket 的路径 const wss = new ws.Server({ server }); // 同时支持 /ws 和 /game 的 WebSocket 链接请求 wss.shouldHandle = (request) => { const path = url.parse(request.url).pathname; request.path = path; return ['/ws', '/game'].indexOf(path) > -1; }; // 监听 WebSocket 链接创建 wss.on('connection', (ws, request) => { // request: 要升级到 WebSocket 协议的 HTTP 链接 // 被升级到 WebSocket 的请求不会被 express 处理, // 须要使用会话中间节获取会话 sessionMiddleware(request, null, () => { const session = request.session; if (!session) { // 没有获取到会话,强制断开 WebSocket 链接 ws.send(JSON.stringify(request.sessionError) || "No session avaliable"); ws.close(); return; } console.log(`WebSocket client connected with openId=${session.userInfo.openId}`); // 根据请求的地址进行不一样处理 switch (request.path) { case '/ws': return serveMessage(ws, session.userInfo); case '/game': return serveGame(ws, session.userInfo); default: return ws.close(); } }); }); // 监听 WebSocket 服务的错误 wss.on('error', (err) => { console.log(err); }); } /** * 进行简单的 WebSocket 服务,对于客户端发来的全部消息都回复回去 */ function serveMessage(ws, userInfo) { // 监听客户端发来的消息 ws.on('message', (message) => { console.log(`WebSocket received: ${message}`); ws.send(`Server: Received(${message})`); }); // 监听关闭事件 ws.on('close', (code, message) => { console.log(`WebSocket client closed (code: ${code}, message: ${message || 'none'})`); }); // 链接后立刻发送 hello 消息给会话对应的用户 ws.send(`Server: 恭喜,${userInfo.nickName}`); } /** * 使用 WebSocket 进行游戏服务 */ function serveGame(ws, userInfo) { const user = { uid: userInfo.openId, uname: userInfo.nickName, uavatar: userInfo.avatarUrl }; // 建立玩家 const player = new HumanPlayer(user, ws); // 玩家上线 player.online(); }
咱们的源码中使用到了 co 进行协程管理,启动游戏服务前,须要先安装:
cd /data/release/weapp npm install co --save
测试游戏服务
重启 Node 服务:
pm2 restart app Use --update-env to update environment variables [PM2] Applying action restartProcessId on app [app](ids: 0) [PM2] [app](0) ✓ ┌──────────┬────┬─────────┬──────┬──────┬────────┬─────────┬────────┬─────┬───────────┬──────┬──────────┐ │ App name │ id │ version │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │ ├──────────┼────┼─────────┼──────┼──────┼────────┼─────────┼────────┼─────┼───────────┼──────┼──────────┤ │ app │ 0 │ 1.0.0 │ fork │ 7931 │ online │ 4 │ 0s │ 0% │ 10.4 MB │ root │ disabled │ └──────────┴────┴─────────┴──────┴──────┴────────┴─────────┴────────┴─────┴───────────┴──────┴──────────┘ Use `pm2 show <id|name>` to get more details about an app
打开配套的小程序,点击 实验四 - 剪刀石头布小游戏
,点击 开始
按钮进行游戏。