Create websocket server

Posted by trent2800 on Tue, 07 Jan 2020 09:06:03 +0100

swoole has built-in websocket server function since version 1.7.9. We only need a few lines of simple PHP code to create an asynchronous non blocking multi process websocket server.

First of all, we create a new project named swoole in the apache workspace, and then create a new ws-server.php file in the workspace. The PHP file mainly creates a websocket server, and the corresponding user's requests are as follows:

<?php 
//Create websocket server object and listen to port 0.0.0.0:9502
$ws_server = new swoole_websocket_server('192.168.1.169', 9502);
//Set parameters of server runtime
$ws_server->set(array(
'daemonize' => true, //As a daemons or not
));
//Listen for WebSocket connection open events
$ws_server->on('open', function ($ws, $request) { 
file_put_contents( __DIR__ .'/log.txt' , $request->fd); 
//$ws->push($request->fd, "Hello, Welcome\n");
});
  //Listen to WebSocket message events
 $ws_server->on('message', function ($ws, $frame) {
pushMessage($ws,$frame);
}); 
//Listen for WebSocket connection closing events
$ws_server->on('close', function ($ws, $fd) { 
echo "client-{$fd} is closed\n"; 
}); 
  
 
$ws_server->start();
 
  
 
//Message push
 
function pushMessage($ws,$frame){
 
$data = $frame->data;
 
$msg = file_get_contents( __DIR__ .'/log.txt');
 
for ($i=1 ; $i<= $msg ; $i++) {
 
$ws->push($i, $frame->fd.' : '.$data);
 
}
 
}


The above code creates a WebSocket server, whose ip address is 192.168.1.169 and port is 9502. These information can be adjusted according to the actual situation.

2. Create chat interaction page

Similarly, in the swoole directory, we create a chat.html file, which is a static HTML 5 page. Its main function is to interact with the websocket server through the websocket protocol of html5. Its contents are as follows:

<!DOCTYPE html>
 
<html>
 
<head>
 
  <title></title>
 
  <meta charset="UTF-8">
 
  <script type="text/javascript">
 
  if(window.WebSocket){
 
  var webSocket = new WebSocket("ws://192.168.1.169:9502");
 
  webSocket.onopen = function (event) {
 
  //webSocket.send("Hello,WebSocket!"); 
 
  };
 
  webSocket.onmessage = function (event) {
 
    var content = document.getElementById('content');
 
    content.innerHTML = content.innerHTML.concat('<p style="margin-left:20px;height:20px;line-height:20px;">
 
    //User ID - '+ event. Data +' < / P > ');
 
  }
 
  
 
  var sendMessage = function(){
 
  var data = document.getElementById('message').value;
 
  webSocket.send(data);
 
  }
 
  }else{
 
  console.log("Your browser does not support WebSocket");
 
  }
 
  </script>
 
</head>
 
<body>
 
<div style="width:600px;margin:0 auto;border:1px solid #ccc;">
 
<div id="content" style="overflow-y:auto;height:300px;"></div>
 
<hr/>
 
<div style="height:40px">
 
<input type="text" id="message" style="margin-left:10px;height:25px;width:450px;">
 
<button οnclick="sendMessage()" style="height:28px;width:75px;">Send out</button>
 
</div>
 
</div>
 
</body>
 
</html>

3, test

So far, the two files we need have been created. Let's test whether we can work as expected.

3.1 start WebSocket server

Switch to the root directory of the project, and execute the ws-server.php script through the PHP command line to start the WebSocket server. The whole command is as follows:

cd /var/www/html/swoole
 
php ws-server.php


3.2 check whether WebSocket server is started successfully

Enter the command: netstat -tunlp|grep 9502

3.3 start chatting

Prepare several more browsers, and then in each browser, enter http://192.168.1.169/swoole/chat.html, each browser is equivalent to a user, and then you can simulate group chat.

In the chat window of Chrome browser, enter "Hello, I'm chrome". At this time, UC and Firefox will see this message in the chat window. Similarly, input information in the chat window of UC and Firefox browsers, and the other two windows can also be seen. Here is a screenshot of one of the chat windows, as follows:

I hope that the above content can help you. Many PHPer will encounter some problems and bottlenecks when they are advanced. There is no sense of direction when they write too much business code. I don't know where to start to improve. I have collated some information about this, including but not limited to: distributed architecture, high scalability, high performance, high concurrency, server performance tuning, TP6, laravel, YII2, Redis, Swoo For advanced advanced dry goods, such as Le, Swoft, Kafka, Mysql optimization, shell script, Docker, microservice, Nginx, etc Click here to get PHP high quality learning materials for free , free to share!
 

Topics: Programming PHP Firefox Windows Apache