php socket编程实例
程序员文章站
2022-04-16 14:53:15
...
因为用到客户端程序与网页三方支付接口交互,我觉得可以这样来简单实现,在三方支付回调页面中放一个socket服务端,客户端程序与这个socket服务端进行交互,以此来进行最终业务逻辑处理。 php中socket编程,简单实例代码如下: 服务端: ?php set_time_limit
因为用到客户端程序与网页三方支付接口交互,我觉得可以这样来简单实现,在三方支付回调页面中放一个socket服务端,客户端程序与这个socket服务端进行交互,以此来进行最终业务逻辑处理。
php中socket编程,简单实例代码如下:
服务端:
set_time_limit(0);
if(!extension_loaded('sockets')){
//die('服务器未加载sockets扩展');
if(strtoupper(substr(PHP_OS, 3)) == “WIN”)
{
dl(‘php_sockets.dll’);
}
else
{
dl(‘sockets.so’);
}
}
$sock = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(!$sock){
die('创建socket失败');
}
if(!socket_bind($sock,$_SERVER['SERVER_ADDR'],9394)){
die('socket绑定失败');
}
if(!socket_listen($sock)){
die('socket监听失败');
}
$client_id = 0;
do{
//阻塞,直到有客户端连接
$connection = socket_accept($sock);
++$client_id;
printf("Socket connected-$client_id\n");
$buffer='Hello, world!';
socket_write($connection, $buffer . "\n");
do{
$buf =socket_read($connection, 1024, PHP_NORMAL_READ);
//退出连接条件
if($buf=="100\n"){
socket_write($connection, 'bye' . "\n");
break;
}
echo $buf;
socket_write($connection, 'copy that' . "\n");
}while(1);
socket_close($connection);
}while(1);
socket_close($sock);
?>
客户端:
if(!extension_loaded('sockets')){
//die('服务器未加载sockets扩展');
if(strtoupper(substr(PHP_OS, 3)) == “WIN”)
{
dl(‘php_sockets.dll’);
}
else
{
dl(‘sockets.so’);
}
}
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(!$socket){
die('创建socket失败');
}
$connection = socket_connect($socket,'localhost', 9394);
$send=0;
do{
$buffer = socket_read($socket, 1024, PHP_NORMAL_READ);
//退出连接条件
if($buffer=="bye\n"){
break;
}
echo $buffer;
++$send;
socket_write($socket, $send . "\n");
}while(1);
socket_close($socket);
?>
与c++程序交互,客户端:
#include
#include
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main(int argc, char* argv[])
{
WSADATA wsaData;
WORD wVersionRequested=MAKEWORD(2,2);
int err = WSAStartup(wVersionRequested,&wsaData);
if (!err)
{
cout"inital socket success"
上一篇: 初级码农与高级码农到底有什么区别