服務端:php
<?php
class Chat
{
const HOST = '0.0.0.0';//ip地址 0.0.0.0表明接受全部ip的訪問
const PART = 8080;//端口號
private $server = null;//單例存放websocket_server對象
public $roles = [
'郭靖','楊過','洪七公','尹志平','趙志敬','丘處機','歐陽鋒','一燈大師','黃藥師'
];
public function __construct()
{
//實例化swoole_websocket_server並存儲在咱們Chat類中的屬性上,達到單例的設計
$this->server = new swoole_websocket_server(self::HOST, self::PART);
//監聽鏈接事件
$this->server->on('open', [$this, 'onOpen']);
//監聽接收消息事件
$this->server->on('message', [$this, 'onMessage']);
//監聽關閉事件
$this->server->on('close', [$this, 'onClose']);
//設置容許訪問靜態文件
$this->server->set([
'document_root' => '/www/chat1',//這裏傳入靜態文件的目錄
'enable_static_handler' => true//容許訪問靜態文件
]);
//開啓服務
$this->server->start();
}
/**
* 鏈接成功回調函數
* @param $server
* @param $request
*/
public function onOpen($server, $request)
{
echo $request->fd . '鏈接了' . PHP_EOL;//打印到咱們終端
$server->push($request->fd,json_encode(['no' => $request->fd, 'msg' =>'']));
}
/**
* 接收到信息的回調函數
* @param $server
* @param $frame
*/
public function onMessage($server, $frame)
{
$role = $this->getRole($frame->fd);
echo $role. '來了,說:' . $frame->data . PHP_EOL;//打印到咱們終端
foreach ($server->connections as $fd) {//遍歷TCP鏈接迭代器,拿到每一個在線的客戶端id
//將客戶端發來的消息,推送給全部用戶,也能夠叫廣播給全部在線客戶端
$msg = $frame->data;
$server->push($fd, json_encode(['no' => $frame->fd,'role'=>$role, 'msg' => $msg]));
}
}
public function getRole($fd)
{
$roles = count($this->roles);
$role = ($fd < $roles) ? $this->roles[$fd] : $this->roles[$fd%$roles];
var_dump($role);
return $role;
}
/**
* 斷開鏈接回調函數
* @param $server
* @param $fd
*/
public function onClose($server, $fd)
{
echo $fd . '走了' . PHP_EOL;//打印到咱們終端
}
}
$obj = new Chat();
客戶端html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>聊天室</title>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<style>
.right {
color: blue;
display:block;
float:right;
width:100%;
}
</style>
<div style="width: 500px; margin:0 auto;">
<div class="log" id='scrolldIV' style="height:500px;border: 2px solid #ccc;line-height: 1.5em;overflow:auto" >
=======聊天室======
</div>
<!--<input type="button" value="鏈接" onClick="link()">-->
<input type="hidden" value="" id="fd">
<!--<input type="button" value="斷開" onClick="dis()">-->
<div >
<input type="text" id="text">
<input type="button" value="發送" onClick="send()" id="submit">
</div>
</div>
<script>
$(document).keydown(function(event){
if(event.keyCode==13){
$("#submit").click();
}
});
$(function () {
$("#text").focus();
link();
})
function link() {
var url = 'ws://192.168.33.60:8080';
socket = new WebSocket(url);
socket.onopen = function (evt) {
log1('<div>鏈接成功</div>')
}
socket.onmessage = function (msg) {
var data = $.parseJSON(msg.data)
if(data.msg.length <= 0){
$("#fd").val(data.no);
} else {
log(data);
}
var div = document.getElementById('scrolldIV');
div.scrollTop = div.scrollHeight;
}
socket.onclose = function () {
log1('<div>斷開鏈接</div>')
}
}
function dis() {
socket.close();
socket = null;
}
function log1(data) {
$('.log').append(data);
}
function log(data) {
var nowFd = $("#fd").val();
console.log(data);
var role;
if(data['no'] == nowFd){
role ="我";
$('.log').append("<div class='right'>" + role+":"+ data['msg'] + '</div>');
} else {
$('.log').append("<div >" + data.role+": "+data['msg'] + '</div>');
}
}
function send() {
var text = $('#text').val();
if(text.length > 0){
socket.send(text);
$("#text").val('');
}
$("#text").focus();
}
function send2() {
var json = JSON.stringify({'type': 'php', 'msg': $('#text2').attr('value')})
socket.send(json);
}
</script>
</body>
</html>
服務端 啓動jquery
php Chat.phpweb
訪問客戶端的html 瀏覽器打開json
參考 https://www.jianshu.com/p/ac77f05bee56瀏覽器