继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

17、Workerman案例4-Websocket服务

Iamasb
关注TA
已关注
手记 25
粉丝 4
获赞 37

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

https://img.mukewang.com/5cdae02a0001570909960148.jpg

  • 运行

https://img4.mukewang.com/5cdae03f00017b3f04730299.jpg

打开App,阅读手记
1人推荐
发表评论
随时随地看视频慕课网APP