• c 写cgi 与socket通信


    服务器端:
    int sock()
    {
    int port=7777;
    struct sockaddr_in sin;
    struct sockaddr_in pin;
    int sock_fp;
    int temp_sock_fp;
    int size_of_addr;
    char *msg="hello internet!"
    char buff[2561];


    sock_fp = socket(AF_INET,SOCK_STREAM,0);
    if(sock_fp==-1)
    {
    perror("socket");
    exit(1);
    }
    bzero(&sin,sizeof(sin));
    sin.sin_family=AF_INET;
    sin.sin_addr.s_addr=INADDR_ANY;
    sin.sin_port = htons(port);

    if(bind(sock_fp,(struct sockaddr *)&sin,sizeof(sin))==-1)
    {
    perror("bind!");
    exit(1);
    }
    if(listen(sock_fp,20)==-1)
    {
    perror("listen!");
    exit(1);
    }
    printf("write to recive:\n");
    while(1)
    {

    temp_sock_fp=accept(sock_fp,(struct sockaddr *)&pin,&size_of_addr);

    if(temp_sock_fp==-1)
    {
    perror("accept!");
    exit(1);
    }
    if(recv(temp_sock_fp,buff,sizeof(buff),0)==-1)
    {
    perror("recv");
    exit(1);
    }
    printf("recv:%x\n",buf);
    webdeal(WebServerComm.currentRead);
    if(send(temp_sock_fp,msg.currentRead,sizeof(msg),0)==-1)
    {
    perror("send");
    exit(1);
    }
    close(temp_sock_fp);
    }

    }

    客户端:
    #include <stdio.h>
    #include "cgic.h"
    #include <string.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <netdb.h>
    #include <stdio.h>
    #include <unistd.h>
    int cgiMain()
    {
    cgiHeaderContentType("text/html");
    Sock();
    return 0;
    }
    int Sock()
    {
    int sock_fp;
    struct sockaddr_in pin;
    struct hostent *server_host_name;
    char *msg="ok,socket!";
    char buff[2561];

    char *host_name = "192.168.2.79";
    int port=7777;

    server_host_name = gethostbyname(host_name);
    if(server_host_name==0) {
    perror("can not resolving localhost\n");
    exit(1);
    }
    bzero(&pin,sizeof(pin));
    pin.sin_family = AF_INET;
    pin.sin_addr.s_addr = htonl(INADDR_ANY);
    pin.sin_port = htons(port);
    sock_fp= socket(AF_INET, SOCK_STREAM, 0);
    if(sock_fp==-1){
    perror("cannot open socket ");
    exit(1);
    }
    if(connect(sock_fp, (void *)&pin, sizeof(pin))==-1)
    {
    perror("con not connecting to server\n");
    }


    if(send(sock_fp,msg,sizeof(msg),0)==-1)
    {
    perror("can not send");
    exit(1);
    }
    if(recv(sock_fp,buff,sizeof(buff),0)!=-1)
    {
    printf("buff=%s\n",buff);

    }
    else
    {
    perror("can not recv\n");
    exit(1);
    }
    close(sock_fp);

    }
  • 相关阅读:
    NW开发教程系列六:表头和表体(多表体)
    Java 正则表达式 量词 --- 三种匹配模式【贪婪型、勉强型、占有型】
    信号量与PV操作
    java的(PO,VO,TO,BO,DAO,POJO)解释
    使用Application对象简单完成网站总访问人数的统计
    更新记录后关闭子窗口并刷新父窗口的Javascript
    jquery jqPlot API 中文使用教程
    一款基于bootstrap的datetimepicker
    2013杭州赛区Ants hdu4776
    openGL中的函数调用类成员函数
  • 原文地址:https://www.cnblogs.com/zzxap/p/2175775.html
Copyright © 2020-2023  润新知