博客首页 注册 建议与交流 排行榜 加入友情链接         宝宝相册的专门空间
推荐 投诉 搜索: 帮助

好想好好爱你!

badb0y.cublog.cn


php和c通过socket通信--udp篇
/*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;
if(!$sock){
    echo "socket create failure";
}
if($buf=="")
    $buf="hello,how are you!\n";
    echo "send error\n";
    socket_close($sock);
    exit();
}
 
$buf="";
$msg="";
    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>
/*这个过程很简单,就是客户端提交一个信息,服务端接收,
并返回给客户端一个"接收到"的确认信息。
*/
 

 原文地址 http://xxx
发表于: 2008-04-17 ,修改于: 2008-04-17 12:27,已浏览161次,有评论0条 推荐 投诉


网友评论

发表评论