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

sock已连接,接收数据有问题,各位帮帮忙
我是想实现收发信息,但是现在就一个字符a由客户端发送,服务器接收到的信息不是a(没显示),sock是连上的。请大家帮帮我。
服务器端程序:
int main( )
{
  unsigned short int port;//端口号
int sock_serv,sock_client;
struct sockaddr_in name_server,name_client;
char m_szIP[20];
char buf[256],buffer;
int i,j,n;
typedef unsigned short int U16;
U16 l_string[100];

  sock_serv=socket(AF_INET,SOCK_STREAM,0);
if(sock_serv<0)
printf("sock_serv error\n");
else
  printf("sock_serv OK\n");

bzero(&name_server,sizeof(name_server));
  name_server.sin_family=AF_INET;
  name_server.sin_port=htons(7070);
name_server.sin_addr.s_addr=htonl(INADDR_ANY);
if(bind(sock_serv,(struct sockaddr *) &name_server,sizeof(name_server))<0)
printf("bind error\n");

listen(sock_serv,LISTENQ);
for(;;)
  {
printf("server waiting\n");

  socklen_t length = sizeof(name_client);

  sock_client = accept(sock_serv,(struct sockaddr*)&name_client,&length);

char msgbuf[150]; 

recv(sock_client,msgbuf,150,0);//接收打印
  printf("REV= %c \n",msgbuf[0]);
}
printf("sock end!\n");
  close(sock_serv);
}

客户端程序

int main(void)//CreateClientSocket
{
int sock_serv,sock_client;
struct sockaddr_in name_server,name_client;
char m_szIP[20];
struct hostent *hp;
char *host;

  host="192.168.0.2";
  if((hp=gethostbyname(host))==NULL)
  printf("Unknown host: %s\n",host);

  sock_client=socket(AF_INET,SOCK_STREAM,0);
if(sock_client<0)
printf("socket error");

  bzero(&name_server,sizeof(name_server));
  name_server.sin_family = AF_INET;
  name_server.sin_port = htons(7070);
  name_server.sin_addr.s_addr = htonl(INADDR_ANY);

  bzero(&sock_client,sizeof(sock_client));
  sock_client.sin_family = AF_INET;
  sock_client.sin_addr.s_addr=((struct in_addr *)(hp->h_addr))->s_addr;
  sock_client.sin_port = htons(7071);

if(bind(sock_client,(struct sockaddr *) &name_server,sizeof(name_server))<0)
printf("bind error\n");
if(connect(sock_client,(struct name *) &name_server,sizeof(name_server))<0)
printf("connect error");
else
  printf("connect!\n");
char msgbuf[150];
  msgbuf[0]='a';
  send(sock_serv,msgbuf,150,0);//发送'a'
printf("Send= %c\n",msgbuf[0]);
  close(sock_client);
}

------解决方案--------------------
你这个代码对吗 我晃眼看了下 
int sock_serv,sock_client; 

bzero(&sock_client,sizeof(sock_client)); 
sock_client.sin_family = AF_INET; 
sock_client.sin_addr.s_addr=((struct in_addr *)(hp->h_addr))->s_addr; 
sock_client.sin_port = htons(7071); 
这是从你代码中的照抄

写混淆了吧