workerman上给的chat例子在win下实现过程
1、html代码
- <html>
- <meta charset="UTF-8">
- <body>
- <div id='tips'></div>
- <ul id="msg">
- </ul>
- <input type="text" id ="say" />
- <input id="submit" onclick="chat()" type="submit">
- </body>
- <script type="text/javascript" src="jquery-2.0.0.min.js" ></script>
- <script>
- var ws;
- $(function(){
- ws = new WebSocket("ws://192.168.10.249:2347");
- ws.onopen = function() {
- $('#tips').html('连接服务器成功!');
- };
- })
- function chat(){
- var txt = $('#say').val();
- if(txt == ''){
- return false;
- }
- ws.send(txt);
- $('#say').val('');
- ws.onmessage = function(e) {
- $('#msg').append('<li>'+e.data+'</li>');
- };
- }
- </script>
- </html>
- 2、php代码
-
- <?php
- use Workerman\Worker;
- require_once '../workerman/Autoloader.php';
- $global_uid = 0;
- function handle_connection($connection)
- {
- global $text_worker, $global_uid;
- $connection->uid = ++$global_uid;
- }
- function handle_message($connection, $data)
- {
- global $text_worker;
- foreach($text_worker->connections as $conn)
- {
- $conn->send("user[{$connection->uid}]: $data ");
- }
- }
- function handle_close($connection)
- {
- global $text_worker;
- foreach($text_worker->connections as $conn)
- {
- $conn->send("user[{$connection->uid}] logout");
- }
- }
- $text_worker = new Worker("websocket://0.0.0.0:2347");
- $text_worker->count = 1;
- $text_worker->onConnect = 'handle_connection';
- $text_worker->onMessage = 'handle_message';
- $text_worker->onClose = 'handle_close';
- Worker::runAll();
-
3、在cmd 命令行运行index.PHP
首先,添加php在环境变量;在cd切换index.php文件所在目录
在php index.php 运行,窗口不能关闭
在浏览器打开多个窗口测试