php socket调用c,php通过socket和c通讯

php和c通过socket通信

/*server.c*/ #include  #include  #include  #include  #include  #include  #include  #include  #include  main(){     int sock;     struct sockaddr_in server,client;     int recvd,snd;     int structlength;     char * server_ip = "128.168.10.1";/*server ip address*/     int port = 8888;     char recvbuf[2000],sendbuf[2000];         char str1[]="I have received: ";     memset((char *)&server,0,sizeof(server));     server.sin_family = AF_INET;     server.sin_addr.s_addr = inet_addr(server_ip);     server.sin_port = htons(port);     memset((char *)&client,0,sizeof(client));     client.sin_family = AF_INET;     client.sin_addr.s_addr = htonl(INADDR_ANY);     client.sin_port = htons(port);          if((sock = socket (AF_INET,SOCK_DGRAM,0)) < 0 ){         printf("socket create error! ");         exit(1);     }          structlength = sizeof(server);     if( bind(sock,(struct sockaddr *) &server,structlength) < 0){         printf("socket bind error! ");         perror("bind");         exit(1);     }     while(1){         structlength = sizeof(client);                          printf("waiting....... ");         recvd = recvfrom(sock,recvbuf,sizeof(recvbuf),0,             (struct sockaddr *) & client,&structlength);         if(recvd < 0){             perror("recvfrom");              exit(EXIT_FAILURE);             }         else{             printf("received:%s ",recvbuf);                      memset(sendbuf,0,strlen(sendbuf));             memcpy(sendbuf,str1,strlen(str1));                                  snd = sendto(sock,sendbuf,strlen(str1),0,             (struct sockaddr *) &client,structlength);             if(snd < 0){             perror("sendto");             exit(1);             }             printf("sendok! ");         }                       }                  close(sock); } /* gcc -o server server.c生成server程序,在服务器端运行./server */ /*client.php*/ $server_ip="128.168.10.1"; $port = 8888; $sock=@socket_create(AF_INET,SOCK_DGRAM,0); if(!$sock){     echo "socket create failure"; } if($buf=="")     $buf="hello,how are you! "; if(!@socket_sendto($sock,$buf,strlen($buf),0,"128.168.10.1",8888)){     echo "send error ";     socket_close($sock);     exit(); } $buf=""; $msg=""; if(!@socket_recvfrom($sock,$msg,256,0,&$server_ip,&$port)){     echo "recvieve error!";     socket_close($sock);     exit(); } echo trim($msg)." "; socket_close($sock); ?> /*这个过程很简单,就是客户端提交一个信息,服务端接收, 并返回给客户端一个"接收到"的确认信息。 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值