Table of Contents
php uses swoole to implement a simple multi-person online chat group. swoole online chat
Home Backend Development PHP Tutorial PHP uses swoole to implement a simple multi-person online chat group, swoole online chat_PHP tutorial

PHP uses swoole to implement a simple multi-person online chat group, swoole online chat_PHP tutorial

Jul 12, 2016 am 09:00 AM
php

php uses swoole to implement a simple multi-person online chat group. swoole online chat

Many details of the chat logic are not implemented, only group messaging is implemented.

php code:

$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;
}
Copy after login

 

Front-end code:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<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> 
<div id="output"></div>
</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>
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1093100.htmlTechArticlephp uses swoole to implement a simple multi-person online chat group. Many details of the swoole online chat logic are not implemented. Only mass sending is implemented. php code: $serv = new swoole_webso...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles