微信小程序搭建服务器

 https://cloud.tencent.com/developer/labs/lab/10004

 

 

https://mp.weixin.qq.com

curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -yum install nodejs -y

server {
        listen 443;
        server_name www.example.com; # 改为绑定证书的域名
        # ssl 配置
        ssl on;
        ssl_certificate 1_www.example.com_bundle.crt; # 改为自己申请得到的 crt 文件的名称
        ssl_certificate_key 2_www.example.com.key; # 改为自己申请得到的 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;
        }
    }

mongod --fork --dbpath /data/mongodb --logpath /data/logs/mongodb/weapp.log

use weapp;
db.createUser({ user: 'weapp', pwd: 'weapp-dev', roles: ['dbAdmin', 'readWrite']});

cd /data/release/weapp
npm install connect-mongo wafer-node-session --save

module.exports = { 
    serverPort: '8765', 

    // 小程序 appId 和 appSecret 
    // 请到 https://mp.weixin.qq.com 获取 AppID 和 AppSecret
    appId: 'YORU_APP_ID', 
    appSecret: 'YOUR_APP_SECRET', 

    // mongodb 连接配置,生产环境请使用更复杂的用户名密码
    mongoHost: '127.0.0.1', 
    mongoPort: '27017', 
    mongoUser: 'weapp', 
    mongoPass: 'weapp-dev', 
    mongoDb: 'weapp'
};

//***********************************************************

// 引用 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}`);

cd /data/release/weapp
npm install ws --save

//*****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

// 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}`);

# WebSocket 配置
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
        listen 443;
        server_name www.example.com; # 改为绑定证书的域名
        # ssl 配置
        ssl on;
        ssl_certificate 1_www.example.com.crt; # 改为自己申请得到的 crt 文件的名称
        ssl_certificate_key 2_www.example.com.key; # 改为自己申请得到的 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;
        }
    }


/**
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 });
        }
    }
}

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);
    }
}

 

​
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);
    }
}

​

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);
    }
}

// 引入 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();
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值