近段时间因为工作需要,学习了php相关的程序设计。其中需要用到php的socket通信,本来php socket通信比C语言还简单,但是server端用C代码实现,client端用php实现,而且要用本地通信的方式,即基于AF_UNIX的形式,通过本地临时文件来进行通信。用C语言实现的话相对较容易,网上资料也较多,在此主要参照:http://blog.csdn.net/ast_224/article/details/3962221,但是用php实现的AF_UNIX方式网上实例代码较少。通过参考php在线参考手册,修改相关参数后,能够基于AF_UNIX实现C-server和php-client通信。代码如下:
server端
参照:http://blog.csdn.net/ast_224/article/details/3962221
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#define UNIX_DOMAIN "/tmp/UNIX.domain"
int main(void)
{
socklen_t clt_addr_len;
int listen_fd;
int com_fd;
int ret;
int i;
static char recv_buf[1024];
int len;
struct sockaddr_un clt_addr;
struct sockaddr_un srv_addr;
listen_fd=socket(PF_UNIX,SOCK_STREAM,0);
if(listen_fd<0)
{
perror("cannot create communication socket");
return 1;
}
else
{
printf("socket start:\n");
}
//set server addr_param
srv_addr.sun_family=AF_UNIX;
strncpy(srv_addr.sun_path,UNIX_DOMAIN,sizeof(srv_addr.sun_path)-1);
unlink(UNIX_DOMAIN);
//bind sockfd & addr
ret=bind(listen_fd,(struct sockaddr*)&srv_addr,sizeof(srv_addr));
if(ret==-1)
{
perror("cannot bind server socket");
close(listen_fd);
unlink(UNIX_DOMAIN);
return 1;
}
else
{
printf("bind ok\n");
}
//listen sockfd
ret=listen(listen_fd,1);
if(ret==-1)
{
perror("cannot listen the client connect request");
close(listen_fd);
unlink(UNIX_DOMAIN);
return 1;
}
else
{
printf("start to listen\n");
}
//have connect request use accept
len=sizeof(clt_addr);
com_fd=accept(listen_fd,(struct sockaddr*)&clt_addr,&len);
if(com_fd<0)
{
perror("cannot accept client connect request");
close(listen_fd);
unlink(UNIX_DOMAIN);
return 1;
}
//read and printf sent client info
printf("/n=====info=====/n");
for(i=0;i<4;i++)
{
memset(recv_buf,0,1024);
int num=read(com_fd,recv_buf,sizeof(recv_buf));
printf("Message from client (%d)) :%s/n",num,recv_buf);
}
close(com_fd);
close(listen_fd);
unlink(UNIX_DOMAIN);
return 0;
}client端:
<?php
define("UNIX_DOMAIN","/tmp/UNIX.domain");
echo UNIX_DOMAIN;
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0); //第三个参数为0
if ($socket < 0)
{
echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
}
else{
echo "create OK.\n";
}
$result = socket_connect($socket, UNIX_DOMAIN); //这里只要两个参数即可
if ($result < 0)
{
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror($result) . "\n";
}
else{
echo "connect OK";
}
//下面的代码和普通php socket通信一致
$in = "Hello,ni hao\n";
if(!socket_write($socket, $in, strlen($in)))
{
echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
}
else{
echo "send message ok!";
}
echo "Close SOCKET...";
socket_close($socket);
echo "Close OK";
?>