免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1028 | 回复: 0
打印 上一主题 下一主题

c 写cgi 与socket通信: [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-03-27 19:14 |只看该作者 |倒序浏览
服务器端:
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
#include "cgic.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include  
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);
}

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/34529/showart_266212.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP