php websocket项目开发,推荐使用:Workerman

本片内容使用Workerman实现了简单的及时聊天功能,具体代码如下:

<?php
// phpinfo();
header('Content-Type: text/html; charset=utf-8'); require 'vendor/autoload.php'; use Workerman\Worker; $sk=new Sock(); //对创建的socket循环进行监听,处理数据
$sk->run(); function array_remove($arr, $key){
if(!array_key_exists($key, $arr)){
return $arr;
}
$keys = array_keys($arr);
$index = array_search($key, $keys);
if($index !== FALSE){
array_splice($arr, $index, 1);
}
return $arr; } class Sock{
public $sockets; //socket的连接池,即client连接进来的socket标志
public $ws_worker; public function __construct(){ // Create a Websocket server
$this->ws_worker = new Worker("websocket://0.0.0.0:8889"); // 4 processes
$this->ws_worker->count = 4; // Emitted when new connection come
$this->ws_worker->onConnect = function($connection)
{
echo "New connection\n";
echo 'id=' . $connection->id . ' ';
$this->sockets[$connection->id] = array('client'=>$connection);
echo 'count=' . count($this->sockets) . ' '; }; // Emitted when data received
$this->ws_worker->onMessage = function($connection, $data)
{
// Send hello $data
echo "\n".$connection->id." -> req: ".$data;
$jdata = json_decode($data,true);
echo "\n op: ".$jdata['op'];
if($jdata['op'] == 'login'){
//{'op':'login','user':user}
$cs = $this->sockets[$connection->id];
$cs['user'] = $jdata['user'];
$this->sockets[$connection->id] = $cs;
$connection->send($jdata['user'].'登录成功');
return;
}else{
// {'op':'chat','from_user':user,'to_user':user,'msg':msg}
$deal = false;
if($jdata['op'] == 'chat'){
foreach ($this->sockets as $key => $value) {
if($value['user'] == $jdata['to_user']){
$value['client']->send($jdata['msg']);
$connection->send($data);
$deal = true;
}
}
if($deal == false){
$connection->send($jdata['user'].'会员不存在');
}
}else{
$connection->send('参数异常: ' . $data);
}
} }; // Emitted when connection closed
$this->ws_worker->onClose = function($connection)
{
echo "Connection closed\n";
$this->sockets = array_remove($this->sockets, $connection->id);
};
} public function run(){
Worker::runAll();
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="jquery.js" type="text/javascript"></script> </head>
<body>
<input type="text" id="input" placeholder="Message…" />
<hr />
<pre id="output"></pre> <script>
var user = '';
var host = 'ws://127.0.0.1:8889';
var socket = null;
var input = document.getElementById('input');
var output = document.getElementById('output');
var print = function (message) {
var samp = document.createElement('samp');
samp.innerHTML = message + '\n';
output.appendChild(samp); return;
}; user = window.prompt("欢迎?","请在此输入您的姓名。"); input.addEventListener('keyup', function (evt) {
if (13 === evt.keyCode) {
var msg = input.value; if (!msg) {
return;
} try {
socket.send(msg);
input.value = '';
input.focus();
} catch (e) {
console.log(e);
} return;
}
}); try {
socket = new WebSocket(host);
socket.onopen = function () {
print('connection is opened');
input.focus();
socket.send('{"op":"login","user":"'+user+'"}');
return;
};
socket.onmessage = function (msg) {
print(msg.data); return;
};
socket.onclose = function () {
print('connection is closed'); return;
}; } catch (e) {
console.log(e);
}
</script>
</body>
</html>

使用 php socket.php 启动服务端。

js端要发起json结构的数据,如下截图:

php websocket的更多相关文章

  1. 漫扯:从polling到Websocket

    Http被设计成了一个单向的通信的协议,即客户端发起一个request,然后服务器回应一个response.这让服务器很为恼火:我特么才是老大,我居然不能给小弟发消息... 轮询 老大发火了,小弟们自 ...

  2. 细说WebSocket - Node篇

    在上一篇提高到了 web 通信的各种方式,包括 轮询.长连接 以及各种 HTML5 中提到的手段.本文将详细描述 WebSocket协议 在 web通讯 中的实现. 一.WebSocket 协议 1. ...

  3. java使用websocket,并且获取HttpSession,源码分析

    转载请在页首注明作者与出处 http://www.cnblogs.com/zhuxiaojie/p/6238826.html 一:本文使用范围 此文不仅仅局限于spring boot,普通的sprin ...

  4. WebSocket - ( 一.概述 )

    说到 WebSocket,不得不提 HTML5,作为近年来Web技术领域最大的改进与变化,包含CSS3.离线与存储.多媒体.连接性( Connectivity )等一系列领域,而即将介绍的 WebSo ...

  5. php+websocket搭建简易聊天室实践

    1.前言 公司游戏里面有个简单的聊天室,了解了之后才知道是node+websocket做的,想想php也来做个简单的聊天室.于是搜集各种资料看文档.找实例自己也写了个简单的聊天室. http连接分为短 ...

  6. Demo源码放送:打通B/S与C/S !让HTML5 WebSocket与.NET Socket公用同一个服务端!

    随着HTML5 WebSocket技术的日益成熟与普及,我们可以借助WebSocket来更加方便地打通BS与CS -- 因为B/S中的WebSocket可以直接连接到C/S的服务端,并进行双向通信.如 ...

  7. Cowboy 开源 WebSocket 网络库

    Cowboy.WebSockets 是一个托管在 GitHub 上的基于 .NET/C# 实现的开源 WebSocket 网络库,其完整的实现了 RFC 6455 (The WebSocket Pro ...

  8. 借助Nodejs探究WebSocket

    文章导读: 一.概述-what's WebSocket? 二.运行在浏览器中的WebSocket客户端+使用ws模块搭建的简单服务器 三.Node中的WebSocket 四.socket.io 五.扩 ...

  9. 细说websocket - php篇

    下面我画了一个图演示 client 和 server 之间建立 websocket 连接时握手部分,这个部分在 node 中可以十分轻松的完成,因为 node 提供的 net 模块已经对 socket ...

  10. webSocket and LKDBHelper的使用说明

    socketket与lkdbhelper来处理数据 客户需求: 当我们有需要从自己的后台推送消息给我们的用户时,用户需要实时的接收到来自我们的推送消息.前提是没有使用第三方的推送框架,那么这个使用we ...

随机推荐

  1. layer结合art实现弹出功能

    模板 <!-- 模板 --> <script id="render-tpl" type="text/html"> <table c ...

  2. http协议详解及htt面试题目,常见的http状态码

    http协议详解及htt面试题目,常见的http状态码 HTTP报文是面向文本的,报文中的每一个字段都是一些ASCII码串,各个字段的长度是不确定的.HTTP有两类报文:请求报文和响应报文. HTTP ...

  3. The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration

    用过Mysql的人都知道,这个时区问题真个磨人的小妖精,哪天一忘记设置了就会出来磨磨你!!! 之前用的解决方法都是在Mysql的配置上添加与时区相关的配置,但是今天看到一篇博客:https://blo ...

  4. .net扩展方法

    http://www.cnblogs.com/landeanfen/p/4632467.html 看了博客才知道定义一个Util工具类并且在工具类里面写静态扩展方法并不是最好的选择.

  5. 深入理解Plasma(四)Plasma Cash

    这一系列文章将围绕以太坊的二层扩容框架 Plasma,介绍其基本运行原理,具体操作细节,安全性讨论以及未来研究方向等.本篇文章主要介绍在 Plasma 框架下的项目 Plasma Cash. 在上一篇 ...

  6. 多组图自动无限循环(swiper轮播)

    前两天的一个项目中遇到多组图片无限轮播,当时采用了swiper 但是没有解决让它无限轮播.今天再次尝试了一下发现是自己的样式写错了.今天在这里写一下,为了给自己一个警醒不要犯同样的错误 首先先引入一下 ...

  7. PDOMySQL实现类, 自动重置无效连接

    PHP连接MySQL时, 有可能因为MySQL的原因,而使得php里生成的连接无效.比如超过8小时, MySQL自动断开空闲连接的问题,虽然可以调高这个时间,但显然这不是比较文艺的实现方式.现在洒家用 ...

  8. nvm 设置 nodejs 默认版本

    nvm 设置 nodejs 默认版本 windows 系统的版本管理软件是nodist mac系统的node版本管理根据是nvm 每次重启vscode软件后,nvm ls 看到的默认版本都会恢复到v5 ...

  9. linux 7.2安装扩展redis

    unzip phpredis-php7.zip cd phpredis-php7 /usr/local/php7./bin/phpize ./configure --with-php-config=/ ...

  10. RK3288 GPIO

    简介GPIO, 全称 General-Purpose Input/Output(通用输入输出),是一种软件运行期间能够动态配置和控制的通用引脚.RK3288有9组 GPIO bank: GPIO0,G ...