| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2275 人关注过本帖
标题:用C语言实现socket通信为什么连接成功但send recv都返回-1呀???
只看楼主 加入收藏
wqr12
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2013-3-3
收藏
 问题点数:0 回复次数:0 
用C语言实现socket通信为什么连接成功但send recv都返回-1呀???
第一次接触,很简单的程序~想了好久呀
代码如下:
/*serve.c*/
#include <stdio.h>   
#include <winsock2.h>  
#define SERVER_PORT 6666
#pragma comment(lib, "ws2_32.lib")
main()
{   int serversock,new_sock,addrlen;
 char ch[20]={"Hello world"};
 SOCKADDR_IN serveraddr,clientaddr;

WSADATA wsadata;
WSAStartup(MAKEWORD(2,1), &wsadata);

 if((serversock=socket(AF_INET,SOCK_STREAM,0))<0)
 {printf("can not create a socket\n");
 exit(1);
 }

  serveraddr.sin_family = AF_INET;  
  serveraddr.sin_port = htons(SERVER_PORT);            
  serveraddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);  


  if(bind(serversock,(SOCKADDR*)&serveraddr,sizeof(serveraddr))<0)
  {printf("can not bind\n");
  exit(1);
  }
  printf("listening...\n");
  listen(serversock,1);
  addrlen=sizeof(serveraddr);
  printf("waiting...\n");
  if(new_sock=accept(serversock,(SOCKADDR*)&clientaddr,&addrlen)<0)
  {printf("can not accept\n");
  exit(1);
  }
  while(1)
  {printf("connected and sending...\n");
  if (send(serversock,ch,20,0)<0)
  {printf("can not send\n");
  break;
  }
  printf("sended\n");}
  closesocket(new_sock);
}

/*client.c*/
#include <stdio.h>   
#include <winsock2.h>  
#define SERVER_PORT 6666
#define SERVER_ADDRESS "59.68.161.199"
#pragma comment(lib, "ws2_32.lib")
main()
{    int clientsock;
    char ch[21];
    int c;
    SOCKADDR_IN serveraddr;
    WSADATA wsadata;
WSAStartup(MAKEWORD(2,1), &wsadata);


    if((clientsock=socket(AF_INET,SOCK_STREAM,0))<0)
    {printf("can not create a socket\n");
    exit(1);
    }
      serveraddr.sin_family = AF_INET;  
      serveraddr.sin_port = htons(SERVER_PORT);                     
      serveraddr.sin_addr.S_un.S_addr = inet_addr(SERVER_ADDRESS);     
   printf("connecting...\n");
   c=connect(clientsock,(SOCKADDR*)&serveraddr,sizeof(serveraddr));
   if(c<0)
   {printf("can not connect\n");
   exit(1);
   }
   while(1)
   {printf("getting\n");
    if((recv(clientsock,ch,21,0))<0)
    {printf("can not receive\n");
    break;
     }
    printf("GOT:%s\n",ch);
   }
   closesocket(clientsock);
}
搜索更多相关主题的帖子: socket comment include create 
2013-05-16 20:10
快速回复:用C语言实现socket通信为什么连接成功但send recv都返回-1呀???
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.031769 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved