Implement socket instances in PHP and ActionScript

Source: Internet
Author: User

This instance uses PHP as the socket server and ActionScript as the Socket Client.

Before implementing the PHP socket server, we need to make some preparations. First, we need to enable socketextension first. Then, we add the php.exeexample to the environment variable path. for example, the path of my php.exe is D:/Wamp/bin/PHP/php5.2.6.

 

PHP server code

Socketstart. php file

<? 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 05: 18: 45z Chen. Qiao $
* @ Copyright (c) 2011
*/

Include_once 'etetserver. php ';
$ Socketstart = new service_socketserver ();

 

Socketserver. php file

<? 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 05: 18: 45z Chen. Qiao $
* @ 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 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 = '123 ';
$ 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 sends the message the first time,
* It need a cross-domain policy files, the socket server must send it, and the client
* Cocould connected successful. If the Socket Client is not the first time to send
* 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, $ Login T = 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 client code

Test. FLA File

Mysocket = new xmlsocket ();
Mysocket. onconnect = function (SUCCESS ){
If (SUCCESS ){
Msgarea.html text + = "<B> server connection established! </B> ";
} Else {
Msgarea.html text + = "<B> server connection failed! </B> ";
}
}

Mysocket. onclose = function (){
Msgarea.html text + = "<B> server connection lost </B> ";
}

Xmlsocket. Prototype. ondata = function (MSG ){
Msgarea.html text + = "<B> receive: </B> ";
Msgarea.html text + = MSG;
};

Mysocket. Connect ("192.168.1.205", 9999 );

Function msggo (){
If (msgsend. Text! = ''){
VaR STR = msgsend. text;
Mysocket. Send (STR );
Msgarea.html text + = "<B> send: </B> ";
Msgarea.html text + = STR;
}
}

Pushmsg. onrelease = function (){
Msggo ();
}

We can also create a PHP file to embed the SWF client into a webpage and run it.

Swfshow. php file

<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>

 

Of course, you should change the above IP address to your own IP address, and you can also set the port. You can also use the domain name, but the Code needs a little change.

After everything is ready, you can run your socket server. Enter PHP socketstart. php In cmd.

 

If you need source code can go to this address download: http://download.csdn.net/source/3148443

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.