PHP入门级使用 - longcnn/websocketd_CN GitHub Wiki

服务端处理

以下为三个服务端示例,各自单独使用。

服务端使用很简单,直接在命令行启动 websocketd,指定这个脚本作为服务,即架设好了一个服务端:

websocketd --port=9501 php chat.php

十秒入门教程,计数服务端count.php

#!/usr/bin/php
<?php

// Copyright 2013 Joe Walnes and the websocketd team.
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Simple example script that counts to 10 at ~2Hz, then stops.

for ($count = 1; $count <= 10; $count++) {
	echo $count . "\n";
	usleep(500000);
}

?>

在服务端打印相关变量dump-env.php

#!/usr/bin/php
<?php

// Copyright 2013 Joe Walnes and the websocketd team.
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Standard CGI(ish) environment variables, as defined in
// http://tools.ietf.org/html/rfc3875
$names = array(
  'AUTH_TYPE',
  'CONTENT_LENGTH',
  'CONTENT_TYPE',
  'GATEWAY_INTERFACE',
  'PATH_INFO',
  'PATH_TRANSLATED',
  'QUERY_STRING',
  'REMOTE_ADDR',
  'REMOTE_HOST',
  'REMOTE_IDENT',
  'REMOTE_PORT',
  'REMOTE_USER',
  'REQUEST_METHOD',
  'REQUEST_URI',
  'SCRIPT_NAME',
  'SERVER_NAME',
  'SERVER_PORT',
  'SERVER_PROTOCOL',
  'SERVER_SOFTWARE',
  'UNIQUE_ID',
  'HTTPS'
);

foreach ($names as $name) {
  $value = isset($_SERVER[$name]) ? $_SERVER[$name] : '<unset>';
	echo $name . '=' . $value . "\n";
}

// Additional HTTP headers
foreach ($_SERVER as $name => $value) {
  if (strpos($name, 'HTTP_') === 0) {
    echo $name . '=' . $value . "\n";
  }
}

欢迎问候服务端 greeter.php

#!/usr/bin/php
<?php

// Copyright 2013 Joe Walnes and the websocketd team.
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// For each line FOO received on STDIN, respond with "Hello FOO!".
$stdin = fopen('php://stdin', 'r');
while ($line = fgets($stdin)) {
	echo 'Hello ' . trim($line) . "!\n";
}

?>

客户端参考

count.html:

<!DOCTYPE html>
<pre id="log"></pre>
<script>
  // helper function: log message to screen
  function log(msg) {
    document.getElementById('log').textContent += msg + '\n';
  }

  // setup websocket with callbacks
  var ws = new WebSocket('ws://localhost:8080/');
  ws.onopen = function() {
    log('CONNECT');
  };
  ws.onclose = function() {
    log('DISCONNECT');
  };
  ws.onmessage = function(event) {
    log('MESSAGE: ' + event.data);
  };
</script>
⚠️ **GitHub.com Fallback** ⚠️