手记

17、Workerman案例4-Websocket服务

1、运行环境

  • php版本>5.3

  • workerman版本为3.5.16

  • 采用源码安装Workerman

  • ip为192.168.0.55

2、代码

  • web服务代码 start_websocket.php

<?php

require_once __DIR__.”/Autoloader.php”;

use Workerman\Worker;

$ws = new Worker(“websocket://0.0.0.0:2348”);

$ws->onConnect = function($connection) {

    echo “new connection”,PHP_EOL;

};

$ws->onMessage = function($connection,$data) {

    $connection->send(“you input data is:”.$data);

};

$ws->onClose = function($connection){

    echo “close connection”,PHP_EOL;

};

Worker::runAll();

  • 修改之前的index.html文件

<!DOCTYPE html>

<html lang=”en”>

<head>

<meta charset=”UTF-8″>

<title>test</title>

</head>

<body>

<h1>this is test</h1>

</body>

<script>

var ws = new WebSocket(“ws://192.168.0.55:2348”);

ws.onopen = function()

{

ws.send(“hello world”);

};

ws.onmessage = function (evt)

{

var received_msg = evt.data;

console.log(“receive…”+received_msg);

};

ws.onclose = function()

{

console.log(“close”);

};

</script>

</html>

3、启动

  • 新开shell终端,运行 php start_websocket.php start

  • 运行

1人推荐
随时随地看视频
慕课网APP