Home >PHP Framework >Workerman >How to configure wss in workerman
How does Workerman create a wss service so that the client can use the wss protocol to connect to the communication, such as connecting to the server in the WeChat applet.
Answer:
wss protocol is actually websocket SSL, which is to add an SSL layer to the websocket protocol, similar to https (http SSL).
So you only need to enable SSL based on the websocket protocol to support the wss protocol. (Recommended learning: workererman tutorial)
Open SSL directly with Workerman
##Preparation:
1. The Workerman version is not less than 3.3.72. PHP has the openssl extension installed 3. The certificate (pem/crt file and key file) has been applied for and placed on the disk Any directoryCode:
<?php require_once __DIR__ . '/Workerman/Autoloader.php'; use Workerman\Worker; // 证书最好是申请的证书 $context = array( // 更多ssl选项请参考手册 http://php.net/manual/zh/context.ssl.php 'ssl' => array( // 请使用绝对路径 'local_cert' => '磁盘路径/server.pem', // 也可以是crt文件 'local_pk' => '磁盘路径/server.key', 'verify_peer' => false, // 'allow_self_signed' => true, //如果是自签名证书需要开启此选项 ) ); // 这里设置的是websocket协议(端口任意,但是需要保证没被其它程序占用) $worker = new Worker('websocket://0.0.0.0:443', $context); // 设置transport开启ssl,websocket+ssl即wss $worker->transport = 'ssl'; $worker->onMessage = function($con, $msg) { $con->send('ok'); }; Worker::runAll();Through the above code, Workerman listens to the wss protocol, and the client can connect to Workerman through the wss protocol to achieve secure instant messaging. .
Test
Open the chrome browser, press F12 to open the debugging console, enter in the Console column (or put the following code into the html page and run it with js)// 证书是会检查域名的,请使用域名连接 ws = new WebSocket("wss://域名"); ws.onopen = function() { alert("连接成功"); ws.send('tom'); alert("给服务端发送一个字符串:tom"); }; ws.onmessage = function(e) { alert("收到服务端的消息:" + e.data); };
Note:
1. If it cannot be started, port 443 is usually occupied. Please change it to another port. Note that the client connects after changing it to other ports. You need to bring the port number. When the client connects, the address is similar to wss://domain.com:xxx, where xxx is the port number. If you must use port 443, please use method 2 proxy to implement wss. 2. The wss port can only be accessed through the wss protocol, and ws cannot access the wss port. 3. Certificates are generally bound to domain names, so when testing, the client please use domain names to connect, and do not use IP to connect. 4. If you are unable to access, please check the server firewall. 5. This method requires PHP version >=5.6, because the WeChat applet requires tls1.2, and versions below PHP5.6 do not support tls1.2.The above is the detailed content of How to configure wss in workerman. For more information, please follow other related articles on the PHP Chinese website!