一、workerman下载,地址:https://github.com/walkor/workerman
二、cd到workerman项目根目录下,在workerman根目录下新建game.php,然后编写五子棋服务端交互代码,最后命令启动已经写好的五子棋服务器
sudo php game.php start
game.php的代码如下:
use Workerman\Worker;
require_once __DIR__ . '/Autoloader.php';
$global_uid = 0;
//棋盘大小,默认15行15列
$global_i = 15;
$global_j = 15;
// 当客户端连上来时分配uid
function handle_connection($connection)
{
global $text_worker, $global_uid, $global_i, $global_j;
// 为这个链接分配一个uid
$connection->uid = ++$global_uid;
$text_worker->uidConnections[$connection->uid] = array('cons' => $connection);
$text_worker->user_data[$connection->uid] = array('playing' => 0, 'name' => 'player' . $connection->uid, 'qipan' => array(), 'type' => 0, 'move' => 0);
$json = array('status' => 1, 'msg' => '', 'data' => array());
$json['data']['name'] = $text_worker->user_data[$connection->uid]['name'];
$connection->send(json_encode($json)); //生成玩家昵称
echo "player {$connection->uid} connected!\n";
//分配对手
foreach ($text_worker->user_data as $k => $val) {
/*var_dump($val['playing']);*/
if ($val['playing'] == 0 && $k != $connection->uid) {
//初始化棋盘
$init_data = array();
for ($i = 0; $i <= $global_i; $i++) {
for ($j = 0; $j <= $global_j; $j++) {
$init_data[$i][$j] = 0;
}
}
$text_worker->user_data[$k]['qipan'] = $init_data;
$text_worker->user_data[$connection->uid]['qipan'] = $init_data;
$text_worker->user_data[$k]['playing'] = $connection->uid;
$text_worker->user_data[$connection->uid]['playing'] = $k;
//分配红黑方
$text_worker->user_data[$k]['type'] = 1;
$text_worker->user_data[$k]['move'] = 1;
$text_worker->user_data[$connection->uid]['type'] = 2;
$text_worker->user_data[$connection->uid]['move'] = 0;
$json = array('status' => 2, 'msg' => '初始化棋盘...', 'data' => array());
$json['data']['qipan'