preparation

  1. Install the PHP and Swoole extensions
  2. Install redis and the PHP Redis extension

The SWOole extension of PHP can be used to build websocket server easily. Of course, children who know network programming and Websocket protocol can also write a Websocket server by themselves. Redis makes it easy to process message queues. The backend code file websocketclient.php:


      

class WebsocketClient {
    public $server;
    public function __construct(a) {
        $this->server = new Swoole\WebSocket\Server("0.0.0.0".9501);
        $this->server->on('open'.function (swoole_websocket_server $server, $request) {});$this->server->on('message'.function (Swoole\WebSocket\Server $server, $frame) {
            $message = explode(':', trim($frame->data));
            $redis = new \Redis;
            $redis->connect('127.0.0.1'.6379);
            // The initial connection receives messages from the other side
            if($message[2= = ='connect'){
            	$server->push($frame->fd,'System message: Connection established...... ');
            	$msg_array = $redis->lRange("msg_by_".$message[1].0.- 1);
            	foreach ($msg_array as $key => $value) {
            		$server->push($request->fd,$value);
            	}
            	$redis->set($message[0],$frame->fd);
            	$redis->set($frame->fd,$message[0]);
            	$redis->delete("msg_by_".$message[1]);
            	return;
            }
            // Send a message when the other party is online
            if($to = $redis->get($message[1])){
            	$server->push($to, $message[2]);
            }else{
            	$redis->rPush("msg_by_".$message[1],$message[2]); }});$this->server->on('close'.function ($ser, $fd) {
            $redis = new \Redis;
            $redis->connect('127.0.0.1'.6379);
            $name = $redis->get($fd);
            $redis->delete($name,$fd);
        });
        $this->server->on('request'.function ($request, $response) {
            // Get the message from get and push it to the user
            $this->server->connections $this->server->connections
            foreach ($this->server->connections as $fd) {
                // You need to check whether the websocket connection is correct, otherwise the push may fail
                if ($this->server->isEstablished($fd)) {
                    $this->server->push($fd, $request->get['message']); }}});$this->server->start(); }}new WebsocketClient();
Copy the code

Run PHP webSocketclient.php from the command line to start the WebSocket server. Then create two static pages to test, socket_client.html


      
<html>
<head>
	<meta charset="utf-8">
	<title>Chat Online</title>
	
	<script type="text/javascript">
		window.onload = function(){
			var sender = "xiaoming";
			var receiver = 'dachun';
			var input = document.getElementById("input");
			input.focus();
			var f = 0;

			// Open a websocket
			var socket = new WebSocket(Ws: / / 192.168.33.10:9501 "");
			socket.onopen = function(){
				socket.send("xiaoming:dachun:connect");
			};

			// Get messages from the server
			socket.onmessage = function(event){
				var msg = event.data;
				if(f! = =2)
				{
					var node = document.createTextNode(receiver);
					var div = document.createElement('div');
					div.style.backgroundColor = '#B0B0B0';
					div.style.color = 'red';
					div.style.textAlign = 'right';				
					div.appendChild(node);
					document.body.insertBefore(div,input);
				}
				var node = document.createTextNode(msg);
				var div = document.createElement('div');		
				div.style.color = 'blue';
				div.style.padding = "10px";
				div.style.textAlign = 'right';				
				div.appendChild(node);
				document.body.insertBefore(div,input);
				input.scrollIntoView();
				f=2;
			};



			// Send a message to the server
			input.onchange = function(){
				var msg = sender + ":" + receiver + ":"+input.value;
				if(f! = =1) {var node = document.createTextNode(sender);
					var div = document.createElement('div');		
					div.style.backgroundColor = '#9933CC';
					div.style.textAlign = 'left';				
					div.style.color = 'black';				
					div.appendChild(node);
					document.body.insertBefore(div,input);
				}

				var node = document.createTextNode(input.value);
				var div = document.createElement('div');		
				div.style.color = 'gray';
				div.style.textAlign = 'left';
				div.style.padding = "10px";				
				div.appendChild(node);
				document.body.insertBefore(div,input);

				socket.send(msg);
				input.value = "";
				f=1;
			};
			
		};
		
	</script>
</head>
<body>
	<div></div>
	<input type="" name="" id="input" style="width: 100%;">
	<! - < button onclick = "sendMessage ()" > submit < / button > -- >
</body>
</html>
Copy the code

The second file is the same as the first, except for the sender and receiver, socket_client2.html:


      
<html>
<head>
	<meta charset="utf-8">
	<title>Chat Online</title>
	
	<script type="text/javascript">
		window.onload = function(){
			var sender = "dachun";
			var receiver = 'xiaoming';
			var input = document.getElementById("input");
			input.focus();
			var f = 0;

			// Open a websocket
			var socket = new WebSocket(Ws: / / 192.168.33.10:9501 "");
			socket.onopen = function(){
				socket.send("dachun:xiaoming:connect");
			};

			// Get messages from the server
			socket.onmessage = function(event){
				var msg = event.data;
				if(f! = =2)
				{
					var node = document.createTextNode(receiver);
					var div = document.createElement('div');
					div.style.backgroundColor = '#B0B0B0';
					div.style.color = 'red';
					div.style.textAlign = 'right';				
					div.appendChild(node);
					document.body.insertBefore(div,input);
				}
				var node = document.createTextNode(msg);
				var div = document.createElement('div');		
				div.style.color = 'blue';
				div.style.padding = "10px";
				div.style.textAlign = 'right';				
				div.appendChild(node);
				document.body.insertBefore(div,input);
				input.scrollIntoView();
				f=2;
			};



			// Send a message to the server
			input.onchange = function(){
				var msg = sender + ":" + receiver + ":"+input.value;
				if(f! = =1) {var node = document.createTextNode(sender);
					var div = document.createElement('div');		
					div.style.backgroundColor = '#9933CC';
					div.style.textAlign = 'left';				
					div.style.color = 'black';				
					div.appendChild(node);
					document.body.insertBefore(div,input);
				}

				var node = document.createTextNode(input.value);
				var div = document.createElement('div');		
				div.style.color = 'gray';
				div.style.textAlign = 'left';
				div.style.padding = "10px";				
				div.appendChild(node);
				document.body.insertBefore(div,input);

				socket.send(msg);
				input.value = "";
				f=1;
			};
			
		};
		
	</script>
</head>
<body>
	<div></div>
	<input type="" name="" id="input" style="width: 100%;">
	<! - < button onclick = "sendMessage ()" > submit < / button > -- >
</body>
</html>
Copy the code

Then open socket_client. HTML and socket_client2.html in your browser and test send: