当前位置: 技术问答>linux和unix
请问为何能send但服务端recv不到?
来源: 互联网 发布时间:2016-02-18
本文导语: linux下的一个简单的socket程序,当我在客户端发送一个字符串到服务端时候,send能成功,显示发送了18个字符,而服务端用recv接收的时候总是接收不到字符串,百思不得其解希望大家指教,代码如下: 服务端: #inclu...
linux下的一个简单的socket程序,当我在客户端发送一个字符串到服务端时候,send能成功,显示发送了18个字符,而服务端用recv接收的时候总是接收不到字符串,百思不得其解希望大家指教,代码如下:
服务端:
#include
#include
#include
#include
#include
#include
#define SERVPORT 1985
int main()
{
struct sockaddr_in servaddr;
int sock_id;
int sock_fd;
char buf[BUFSIZ];
FILE *sock_fpi,*sock_fpo;
int num;
sock_id = socket( PF_INET,SOCK_STREAM,0 );
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(SERVPORT);
servaddr.sin_family = AF_INET;
bind( sock_id,(struct sockaddr *)&servaddr,sizeof(servaddr) );
listen( sock_id,1 );
while(1)
{
sock_fd = accept( sock_id,NULL,NULL );
printf("acceptn");
num = recv( sock_fd,buf,strlen(buf),0 );
printf("recieve num: %dn",num);
close(sock_fd);
}
return 0;
}
客户端:
#include
#include
#include
#include
#include
#include
#define SERVPORT 1985
int main()
{
struct sockaddr_in servaddr;
int sock_fd;
char buf[BUFSIZ] = "from clnt message!";
char new[BUFSIZ];
int num;
sock_fd = socket( PF_INET,SOCK_STREAM,0 );
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(SERVPORT);
servaddr.sin_family = AF_INET;
connect( sock_fd,(struct sockaddr *)&servaddr,sizeof(servaddr) );
num = send( sock_fd,buf,strlen(buf),0 );
printf("send num: %d gen",num);
close(sock_fd);
return 0;
}
服务端:
#include
#include
#include
#include
#include
#include
#define SERVPORT 1985
int main()
{
struct sockaddr_in servaddr;
int sock_id;
int sock_fd;
char buf[BUFSIZ];
FILE *sock_fpi,*sock_fpo;
int num;
sock_id = socket( PF_INET,SOCK_STREAM,0 );
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(SERVPORT);
servaddr.sin_family = AF_INET;
bind( sock_id,(struct sockaddr *)&servaddr,sizeof(servaddr) );
listen( sock_id,1 );
while(1)
{
sock_fd = accept( sock_id,NULL,NULL );
printf("acceptn");
num = recv( sock_fd,buf,strlen(buf),0 );
printf("recieve num: %dn",num);
close(sock_fd);
}
return 0;
}
客户端:
#include
#include
#include
#include
#include
#include
#define SERVPORT 1985
int main()
{
struct sockaddr_in servaddr;
int sock_fd;
char buf[BUFSIZ] = "from clnt message!";
char new[BUFSIZ];
int num;
sock_fd = socket( PF_INET,SOCK_STREAM,0 );
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(SERVPORT);
servaddr.sin_family = AF_INET;
connect( sock_fd,(struct sockaddr *)&servaddr,sizeof(servaddr) );
num = send( sock_fd,buf,strlen(buf),0 );
printf("send num: %d gen",num);
close(sock_fd);
return 0;
}
|
num = recv( sock_fd,buf,strlen(buf),0 );
改为:
num = recv( sock_fd,buf,BUFSIZ,0 );
改为:
num = recv( sock_fd,buf,BUFSIZ,0 );