日期:2014-05-16  浏览次数:20754 次

sokcet小问题,让大家见笑了
这是个很间的socket tcp通信,没有使用select模式,其中IP和端口号都已经写死了,问题是在服务器端,没有打印,它就接收不到数据,recv是个阻塞函数
这个问题,我原来好像遇到过,现在又遇到有点小郁闷,有谁知道的啊,给我解答下,谢谢了
client:
#include <netinet/in.h> // for sockaddr_in
#include <sys/types.h> // for socket
#include <sys/socket.h> // for socket
#include <stdio.h> // for printf
#include <stdlib.h> // for exit
#include <string.h> // for bzero
#include <errno.h>
#include <arpa/inet.h>
int main(int argc , char** argv)
{
  int iclient_socket = socket(PF_INET,SOCK_STREAM,0);
  if(-1 == iclient_socket ) 
  {
  perror("create socket fail");
  return -1;
  }  
 
  struct sockaddr_in client_addr;
  bzero(&client_addr,sizeof(client_addr));
  client_addr.sin_family = AF_INET;
  client_addr.sin_addr.s_addr = htons(INADDR_ANY);
  client_addr.sin_port = htons(0);

  if( -1 == bind(iclient_socket,(struct sockaddr*)&client_addr,sizeof(client_addr)))
  {
  printf("Client Bind Port Failed!\n"); 
  exit(1);
  }
   
  struct sockaddr_in server_addr;
  bzero(&server_addr,sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  char chip[]="10.41.28.75";
  if( 0 == inet_aton(chip,&server_addr.sin_addr) ) 
  {
printf("Server IP Address Error!\n");
exit(1);
  }
  server_addr.sin_port = htons(10242);
  socklen_t sock_length = sizeof(server_addr);
  
  if( 0 > connect(iclient_socket,(struct sockaddr*)&server_addr,sock_length) )
  {
  printf("connect error\n");
  }
  else
  {
  printf("connect success\n");
  }
  while(1)
  {
  char chbuffer[256] = {0};
  scanf("%s",chbuffer);
  ssize_t sendcount = send(iclient_socket,chbuffer,sizeof(chbuffer),0);
  if( 0 > sendcount)
  printf("send error\n");
  else
{
printf("send success\n");
}
  }
  //close(iclient_socket); 
  return 0;
}


重点在server:
#include <netinet/in.h> // for sockaddr_in
#include <sys/types.h> // for socket
#include <sys/socket.h> // for socket
#include <stdio.h> // for printf
#include <stdlib.h> // for exit
#include <string.h> // for bzero
#include <errno.h>
int main()
{
  int iserver_socket = socket(PF_INET,SOCK_STREAM,0);
  if( -1 == iserver_socket )
  {
  printf("create socket fail,erroNO:%d<----->%s",errno,strerror(errno));
  }
   
  //bind socket
  struct sockaddr_in server_addr;
  bzero(&server_addr,sizeof(server_addr)); 
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = htons(INADDR_ANY);
  server_addr.sin_port = htons(10242); 
  if( -1 == bind(iserver_socket,(struct sockaddr *)&server_addr,sizeof(server_addr)))
  {
  perror("bind error");
  }

  //listen
  if( -1 == listen(iserver_socket,1))
  {
  printf