php和actionscript实现socket实例

      这个实例是以php作为socket服务器,actionscript作为socket客户端

      在实现php socket服务器之前,我们先要做点准备工作。首先我们要先打开socket扩展,然后我们将php.exe的路径加入环境变量path中,例如,我的php.exe的路径为:D:/wamp/bin/php/php5.2.6

 

php服务器代码

SocketStart.php文件

<?php
/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 *
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @category    Superwar
 * @package     Application
 * @subpackage  Service
 * @author      Chen Qiao <chen.qiao@evebit.com>
 * @version     $$Id: SocketStart.php 171 2011-03-25 05:18:45Z chen.qiao $$
 * @copyright   Copyright (c) 2011
*/

include_once 'SocketServer.php';
$socketStart = new Service_SocketServer();

 

SocketServer.php文件

<?php
/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 *
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @category    Superwar
 * @package     Application
 * @subpackage  Service
 * @author      Chen Qiao <chen.qiao@evebit.com>
 * @version     $$Id: SocketServer.php 171 2011-03-25 05:18:45Z chen.qiao $$
 * @copyright   Copyright (c) 2011
*/

/**
 * socket server class
 *
 * create a socket server and get the message from the client,decode it and
 * send to resulte to client,when the client socket is removed,give the message
 *
 * @package     Information
 * @subpackage  Controller
 * @author      Chen Qiao <chen.qiao@evebit.com>
 * @version     $$Id: PlannerController.php 171 2011-03-25 05:18:45Z chen.qiao $$
 */

class Service_SocketServer
{    
    private $_host;
    private $_port;
    private $_masterSocket;
    private $_currentSockets;
    public static $onlineUserArr = array();
    
    /**
     * __construct of the class
     */
    public function __construct(){
        error_reporting(E_ALL);
        set_time_limit(0);
        ob_implicit_flush();
        /*
         * the host of the socket sever,and also you can use the domain name,and you
         * must change the initSocket function
         */
        $this->_host = '192.168.1.205';
        $this->_port = '9999';
        $this->initSocket();
        $this->_currentSockets = array();
        $this->_currentSockets[] = $this->_masterSocket;
        $this->listenToSockets();
    }
    
    /**
     * create the socket,set option,bind and listen to all socket client
     */
    private function initSocket(){
        if(($this->_masterSocket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
             echo '[SocketServer.initSocket]'.'socket_create()
             failed, reason: ' . socket_strerror($this->_masterSocket);
        } else {
            echo '[SocketServer.initSocket]  socket server create  success.';
        }
        socket_set_option($this->_masterSocket, SOL_SOCKET,SO_REUSEADDR, 1);
        if(($ret = socket_bind($this->_masterSocket, $this->_host, $this->_port)) < 0) {
            echo '[SocketServer.initSocket] '.'socket_bind() failed,
            reason: ' . socket_strerror($ret);
        }
        if(($ret = socket_listen($this->_masterSocket, 5)) < 0) {
            echo '[SocketServer.initSocket] '.'socket_listen()
            failed, reason: ' . socket_strerror($ret);    
        }
    }
    
    /**
     * decode the client message,when the socket client send the message the first time,
     * it need a cross-domain policy files,the socket server must send it,and the client
     * could connected successful.if the socket client is not the first time to send the
     * message,you will decode the message,and return the corresponding message
     *
     * @param resource|array $socket
     * @param string $data
     */
    private function parseRequest($socket, $data){
        if(substr($data,0, 22) == '<policy-file-request/>') {
            $crossFile = '<cross-domain-policy><allow-access-from domain="*"
            to-ports="*"/></cross-domain-policy>';
            $this->sendMessage($socket,$crossFile);    
            return;    
        } else {
//            $socketData = json_decode($data);
            if(!$data) {
                $socketStr = substr($data, 0 ,strlen($data) - 1);
            } else {
                $socketStr = substr($data, 2 ,strlen($data));
            }
//            $socketData = json_decode($socketStr);
            $this->saveDataAndLoad($socket,$socketStr);
        }
    }
    
    /**
     * send the message to socket client
     *
     * @param resource|array $socket
     * @param string $message
     */
    public function sendMessage($sockets, $message){
        $message .= "\0";
        if(!is_array($sockets)) {
            $sockets = array($sockets);
        }
        foreach($sockets as $socket) {
            if($socket === NULL || $socket == '') {
                continue;
            }
            socket_write($socket, $message);
            echo '[SocketServer.SendMessage] Wrote : '.$message.' to ' . $socket;
        }
    }
    
    /**
     * listen to the socket,the socket server can listen to the socket client,if one client socket
     * is connected,we listen to it and receive the message and to decode it,if the client socket
     * is removed,we give the message and close the client socket
     */
    private function listenToSockets(){
        while (true) {
            $changedSockets = $this->_currentSockets;
            $num_changed_sockets = socket_select($changedSockets, $write = NULL, $except = NULL, NULL);
            foreach($changedSockets as $socket)
            {
                if ($socket == $this->_masterSocket) {
                    if (($client = socket_accept($this->_masterSocket)) < 0) {
                        echo '[SocketServer.listenToSockets] '.
                        'socket_accept() failed: reason: ' . socket_strerror($socket);
                        continue;
                    } else {
                        $this->_currentSockets[] = $client;
                        socket_getpeername($client, $newClientAddress);
                        echo '[SocketServer.listenToSockets] '.
                        'NEW CLIENT '.$client.' [IP: '.$newClientAddress.']';
                        $this->addOnlineUserInfo($client);
                    }
                } else {
                     $bytes = socket_recv($socket, $buffer, 4096, 0);
                    if ($bytes == 0) {
                        echo  '[SocketServer.listenToSockets] '.
                        'REMOVING CLIENT '.$socket;
                        $index = array_search($socket, $this->_currentSockets);
                        unset($this->_currentSockets[$index]);    
                        $this->deleteUserFromOnline($socket);            
                        socket_close($socket);
                    }else{                        
                        $this->parseRequest($socket,$buffer);
                    }
                }
            }
            
        }
    }
    
    /**
     * the socket server receive the message from the socket client and decode it,
     * and return the message to client
     *
     * @param resource|array $socket
     * @param string $socketData
     */
    private function saveDataAndLoad($socket,$socketData){
        if($socketData) {
            $this->sendMessage(self::$onlineUserArr, $socketData);
        }
    }
    
    /**
     * if one user is login success , add the socket resource to online user array
     *
     * @param resource $socket
     */
    private function addOnlineUserInfo($socket) {
        echo '[SocketServer.addOnlineUserInfo] '.
                        'Add User To Online User Array';
        self::$onlineUserArr[] = $socket;
    }
    
    /**
     * if one user is login success , add the socket resource to online user array
     *
     * @param resource $socket
     */
    private function deleteUserFromOnline($socket) {
        echo '[SocketServer.deleteUserFromOnline] '.
                        'Delete User From Online User';
        foreach(self::$onlineUserArr as $key=>$online) {
            if($socket == $online) {
                unset(self::$onlineUserArr[$key]);
            }
        }
    }
    
}

 

 

actionscript客户端代码

test.fla文件

mySocket = new XMLSocket();
    mySocket.onConnect = function(success) {
    if (success) {
                    msgArea.htmlText += "<b>Server connection established!</b>";
                } else {
                    msgArea.htmlText += "<b>Server connection failed!</b>";
                }
            }
           
            mySocket.onClose = function() {
                msgArea.htmlText += "<b>Server connection lost</b>";
            }
           
            XMLSocket.prototype.onData = function(msg) {
                msgArea.htmlText += "<b>receive:</b>";
                msgArea.htmlText += msg;
            };
           
            mySocket.connect("192.168.1.205", 9999);
           
            function msgGO() {
                if(msgSend.text != ''){                   
                    var str = msgSend.text;
                    mySocket.send(str);
                    msgArea.htmlText += "<b>send:</b>";
                    msgArea.htmlText += str;
                }
            }
           
            pushMsg.onRelease = function() {
                msgGO();
            }

我们还可以新建一个php文件将此swf客户端嵌入网页中运行

swfShow.php文件

<script type="text/javascript">
function setFlashFocus()
{
    document.getElementById('SuperWar').focus();
}
</script>
<br/>
<div id="putswf" class = "putswf">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="SuperWar" width="760" height="600"
codebase=" http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
<param name="movie" value="test.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#869ca7" />
<param name="allowScriptAccess" value="sameDomain" />
<embed src="test.swf" quality="high" bgcolor="#869ca7" width="760"
height="600" name="demo" align="middle" play="true" loop="false" quality="high"
allowScriptAccess="sameDomain" type="application/x-shockwave-flash"
pluginspage=" http://www.macromedia.com/go/getflashplayer" ></embed>
</object>
</div>

 

当然,上面的ip你应该改为自己的ip,端口也可以自己设置。而且你还可以使用域名,但是代码需要一点小改动。

一切准备就绪之后,你就可以去运行你的socket服务器了,在cmd中输入php socketStart.php即可。

 

如果需要源码的话可以去此地址下载:http://download.csdn.net/source/3148443

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值