用Swoole来写个联机对战游戏呀!(五)联机初始化

栏目: PHP · 发布时间: 4年前

内容简介:教程使用以下是一些有可能有帮助的资料:童鞋们也可以像我一样在

教程使用 Swoole 4.3.0 版本开发,但并没有使用协程等功能,只是使用了 WebSocket Server ,理论上安装旧版也是没问题的。环境需要大家自行安装,这个也是学习的一个过程。

以下是一些有可能有帮助的资料:

童鞋们也可以像我一样在 Windows 使用 PHPStorm 进行开发,再通过一些方法如 共享文件夹WinSCP工具 将项目在 CentOS 中运行起来。

安装swoole-ide-helper扩展

使用 PHPStorm 来开发 Swoole 项目的童鞋,如果不想面向运气编程的话,最好安装一个 swoole-ide-Helper 扩展来协作开发。

在项目根目录运行以下命令:

composer require --dev "eaglewu/swoole-ide-helper:dev-master"
复制代码

安装完毕我们就可以愉快地编写 Swoole 代码了。

服务端基本架构

赵童鞋设想的基本架构需要三个层,他们分别是:

Swoole WebSocket

管理这三个层分别需要三个类: ServerLogicDataCenter

其中最重要的就是 Server 类,它的作用就是作为服务端和客户端的消息交换中心,我们先来写一个初始化的 Server 类,在项目 app 目录新建 Server.php

  1. 使用面向对象的方式实现一个 WebSocket Server 类。
  2. 分别绑定 startworkerStartopenmessageclose 回调方法
  3. 在类中引入 composer 自动加载机制。
  4. WebSocket 对象设置4个 worker 进程。

Server 类:

<?php
require_once __DIR__ . '/../vendor/autoload.php';

class Server
{
    const HOST = '0.0.0.0';
    const PORT = 8811;
    const CONFIG = [
        'worker_num' => 4,
    ];

    private $ws;

    public function __construct()
    {
        $this->ws = new \Swoole\WebSocket\Server(self::HOST, self::PORT);
        $this->ws->set(self::CONFIG);
        $this->ws->on('start', [$this, 'onStart']);
        $this->ws->on('workerStart', [$this, 'onWorkerStart']);
        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);
        $this->ws->start();
    }

    public function onStart($server)
    {
        swoole_set_process_name('hide-and-seek');
        echo sprintf("master start (listening on %s:%d)\n",
            self::HOST, self::PORT);
    }

    public function onWorkerStart($server, $workerId)
    {
        echo "server: onWorkStart,worker_id:{$server->worker_id}\n";
    }

    public function onOpen($server, $request)
    {

    }

    public function onClose($server, $fd)
    {

    }

    public function onMessage($server, $request)
    {

    }
}
new Server();
复制代码

我们来运行一下 Server.php 文件,顺便检验一下 Swoole 扩展是否运行正常,在项目 app 目录下,运行 php Server

  • 后面所有启动 Server 操作都是基于 CentOS 环境
[root@localhost app]# php Server.php 
master start (listening on 0.0.0.0:8811)
server: onWorkStart,worker_id:0
server: onWorkStart,worker_id:1
server: onWorkStart,worker_id:2
server: onWorkStart,worker_id:3
复制代码

如果输出以上信息,就代表 Server 运行成功。

Logic 类和 DataCenter 类属于游戏管理类,在 Manager 文件夹下新建 Logic.phpDataCenter.php 文件,并在 Datacenter 类中增加一个格式化输出日志的 log() 方法。

Logic 类:

<?php
namespace App\Manager;

class Logic
{
}
复制代码

DataCenter 类:

<?php
namespace App\Manager;

class DataCenter
{
    public static function log($info, $context = [], $level = 'INFO')
    {
        if ($context) {
            echo sprintf("[%s][%s]: %s %s\n", date('Y-m-d H:i:s'), $level, $info,
            		json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
        } else {
            echo sprintf("[%s][%s]: %s\n", date('Y-m-d H:i:s'), $level, $info);
        }
    }
}
复制代码

前端初始化

前端我们将会使用 Vue 框架来开发,项目只使用到了 v-ifv-for<template>WebSocket 技术。如果没有接触过前端框架的童鞋,可以尝试阅读官方文档。

在项目根目录创建 frontend 文件夹,并在其中创建 index.html 文件,进行前端初始化。

  1. 使用 CDN 的形式引入 Vue 框架。
  2. 根据 Vue 官方文档,编写一个 HelloWorld 页面。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HideAndSeek</title>
    <script src="https://cdn.bootcss.com/vue/2.6.10/vue.js"></script>
    <link rel="icon" href="data:;base64,=">
</head>
<body>

<div id="app">
    {{ message }}
</div>

<script>
    var app = new Vue({
        el: '#app',
        data: {
            message: 'Hello Vue!'
        }
    })
</script>
</body>
</html>
复制代码

前端的 HelloWorld 页面我们也有了,但是我们要怎么通过 HTTP 请求获取到这个页面呢?这时候就需要使用 SwooleStatic Handler 功能。

  1. 根据官方文档添加 Swoole Static Handler 配置。
  2. Server 新增一个监听端口 8812 ,用于处理HTTP请求。

Server 类:

const FRONT_PORT = 8812;
const CONFIG = [
    ...
    'enable_static_handler' => true,
    'document_root' =>
        '/mnt/htdocs/HideAndSeek_teach/frontend',
];

public function __construct()
{
    ...
    $this->ws->listen(self::HOST, self::FRONT_PORT, SWOOLE_SOCK_TCP);
    ...
}
复制代码

记得将代码中的 document_root 改为自己项目的前端目录哦。

添加完以上代码后,在虚拟机中运行 Server ,并尝试通过浏览器访问 http://虚拟机ip:8812/index.html 浏览前端页面。

用Swoole来写个联机对战游戏呀!(五)联机初始化

看到以上画面就代表访问成功。

WebSocket初始化

现在项目的服务端有了,前端页面有了,就差一个桥梁把他们连接起来,这个桥梁就是 WebSocket 通信机制,项目使用到了简单的 websock.onmessagewebsock.onopenwebsock.onerrorwebsock.onclose

以下是一些有可能有帮助的资料。

  1. Vue 实例新增 data 属性 websock ,在 Vue 实例创建完毕后,初始化 WebSocket 连接服务端并绑定上述四个方法。
  2. WebSocket 对象建立连接后,立刻发送消息到服务端。
  3. 服务端接收到客户端发送的消息后,通过客户端的 fd 返回一条消息。
  4. 服务端增加客户端连接日志输出。
  5. 在页面关闭时,断开 WebSocket 连接。

本章项目初始化就到这里啦,请童鞋们尽量完成自己的Homework后,再进入下一章的学习。

当前项目结构:

HideAndSeek
├── app
│   ├── Manager
│   │   ├── DataCenter.php
│   │   ├── Game.php
│   │   └── Logic.php
│   ├── Model
│   │   ├── Map.php
│   │   └── Player.php
│   └── Server.php
├── composer.json
├── composer.lock
├── frontend
│   └── index.html
├── test.php
└── vendor
    ├── autoload.php
    └── composer

复制代码
用Swoole来写个联机对战游戏呀!(五)联机初始化

以上所述就是小编给大家介绍的《用Swoole来写个联机对战游戏呀!(五)联机初始化》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

C语言基础

C语言基础

安博教育集团 / 2012-2 / 37.00元

《C语言基础》深入浅出地介绍了C语言程序设计的基础知识,内容涉及C语言基础、算法基础、变量、数据类型、运算符、输入/输出相关函数、选择结构、循环结构、各种表达式、数组、字符串、指针、函数、结构体、ISO C99的扩展语法等。全书内容丰富,结构严谨,层次清晰,语言生动,论述精准而深刻,实例丰富而实用。 《C语言基础》不仅适合用做计算机职业培训的首选教材,也可作为普通高校教材使用,更是C语言初学......一起来看看 《C语言基础》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具