本篇文章主要介紹PHP+swoole實現聊天羣發功能,感興趣的朋友參考下,但願對你們有所幫助。javascript
php代碼:php
$serv = new swoole_websocket_server("127.0.0.1",3999);
//服務的基本設置
$serv->set(array(
'worker_num' => 2,
'reactor_num'=>8,
'task_worker_num'=>1,
'dispatch_mode' => 2,
'debug_mode'=> 1,
'daemonize' => true,
'log_file' => __DIR__.'/log/webs_swoole.log',
'heartbeat_check_interval' => 60,
'heartbeat_idle_time' => 600,
));
$serv->on('connect', function ($serv,$fd){
// echo "client:$fd Connect.".PHP_EOL;
});
//測試receive
$serv->on("receive",function(swoole_server $serv,$fd,$from_id,$data){
// echo "receive#{$from_id}: receive $data ".PHP_EOL;
});
$serv->on('open', function($server, $req) {
// echo "server#{$server->worker_pid}: handshake success with fd#{$req->fd}".PHP_EOL;;
// echo PHP_EOL;
});
$serv->on('message',function($server,$frame) {
// echo "message: ".$frame->data.PHP_EOL;
$msg=json_decode($frame->data,true);
switch ($msg['type']){
case 'login':
$server->push($frame->fd,"歡迎歡迎~");
break;
default:
break;
}
$msg['fd']=$frame->fd;
$server->task($msg);
});
$serv->on("workerstart",function($server,$workerid){
// echo "workerstart: ".$workerid.PHP_EOL;
// echo PHP_EOL;
});
$serv->on("task","on_task");
$serv->on("finish",function($serv,$task_id,$data){
return ;
});
$serv->on('close', function($server,$fd,$from_id) {
// echo "connection close: ".$fd.PHP_EOL;
// echo PHP_EOL;
});
$serv->start();
function on_task($serv,$task_id,$from_id,$data) {
switch ($data['type']){
case 'login':
$send_msg="說:我來了~";
break;
default:
$send_msg="說:{$data['msg']['speak']}";
break;
}
foreach ($serv->connections as $conn){
if ($conn!=$data['fd']){
if (strpos($data['msg']['name'],"遊客")===0){
$name=$data['msg']['name']."_".$data['fd'];
}else{
$name=$data['msg']['name'];
}
}else{
$name="我";
}
$serv->push($conn,$name.$send_msg);
}
return;
}
function on_finish($serv,$task_id,$data){
return true;
}
前端代碼:html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WebSocket測試</title>
<script language="javascript"type="text/javascript" src="jquery-1.12.0.min.js">
</script>
</head>
<body>
<h2>WebSocket Test</h2>
暱稱:<input type="text" id="name" size="5" value="遊客"/> <input type="text" id="content">
<button onclick="speak_to_all()">發送</button>
<br/><br/>
<textarea id="message" style="overflow-x:hidden" rows="10" cols="50"></textarea>
<p id="output"></p>
</body>
<script language="javascript"type="text/javascript">
var wsUri ="ws://127.0.0.1:3999/";
var output;
function init() {
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket(wsUri);
websocket.onopen = function(evt) {
onOpen(evt)
};
websocket.onclose = function(evt) {
onClose(evt)
};
websocket.onmessage = function(evt) {
onMessage(evt)
};
websocket.onerror = function(evt) {
onError(evt)
};
}
function get_speak_msg(){
var name=document.getElementById("name").value;
var speak=document.getElementById("content").value;
var json_msg='{"name":"'+name+'","speak":\"'+speak+'"}';
return json_msg;
}
function pack_msg(type,msg){
return '{"type":"'+type+'","msg":'+msg+'}';
}
function onOpen(evt) {
append_speak("已經聯通服務器.........");
speak_msg=get_speak_msg();
send_msg=pack_msg("login",speak_msg);
doSend(send_msg);
}
function onClose(evt) {
append_speak("俺老孫去也!");
}
function onMessage(evt) {
append_speak(evt.data);
}
function onError(evt) {
alert(evt.data);
}
function doSend(message) {
websocket.send(message);
}
function append_speak(new_msg){
document.getElementById("message").value=document.getElementById("message").value+new_msg+"\n";
document.getElementById('message').scrollTop = document.getElementById('message').scrollHeight;
}
function speak_to_all(){
send_msg=pack_msg("speak",get_speak_msg());
if(document.getElementById("content").value==""){
return;
}
doSend(send_msg);
document.getElementById("content").value="";
}
init();
</script>
</html>
總結:以上就是本篇文的所有內容,但願能對你們的學習有所幫助。前端
以上內容但願幫助到你們,不少PHPer在進階的時候總會遇到一些問題和瓶頸,業務代碼寫多了沒有方向感,不知道該從那裏入手去提高,對此我整理了一些資料,包括但不限於:分佈式架構、高可擴展、高性能、高併發、服務器性能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell腳本、Docker、微服務、Nginx等多個知識點高級進階乾貨須要的能夠免費分享給你們,須要的能夠加入個人官方羣點擊此處。java