程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> ASP編程 >> ASP技巧 >> PHP和C通過Socket通信--UDP篇

PHP和C通過Socket通信--UDP篇

編輯:ASP技巧

/*server.c*/
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

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:\n";

     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!\n");
         exit(1);
     }   
     structlength = sizeof(server);
     if( bind(sock,(struct sockaddr *) &server,structlength) < 0){
         printf("socket bind error!\n");
         perror("bind");
         exit(1);
     }

     while(1){
         structlength = sizeof(clIEnt);   
           
         printf("waiting.......\n");
         recvd = recvfrom(sock,recvbuf,sizeof(recvbuf),0,
             (struct sockaddr *) & clIEnt,&structlength);
         if(recvd < 0){
             perror("recvfrom");
             exit(EXIT_FAILURE);   
         }
         else{
             printf("received:%s\n",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!\n");
         }          
     }        
     close(sock);
}
/*
gcc -o server server.c生成server程序,在服務器端運行./server
*/
/*clIEnt.PHP*/

<?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!\n";
if(!@socket_sendto($sock,$buf,strlen($buf),0,"128.168.10.1",8888)){
     echo "send error\n";
     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)."\n";
socket_close($sock);
?>
<form action="clIEnt.PHP" method="post">
<input type=text name=buf>
<input type=submit value="submit">
</form>

/*這個過程很簡單,就是客戶端提交一個信息,服務端接收,
並返回給客戶端一個"接收到"的確認信息。
*/

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved