Linux TCP编程问题
刚学linux 网络编程,写了个小程序:为什么运行到服务器端的recv处就阻塞了呢?苦苦找了好久,真的快崩溃了。。。
求助了!
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX_BUF 50
#define PORT 8300
int main(void)
{
int serverfd,clientfd;
struct sockaddr_in saddr,caddr;
char buf[30];
socklen_t slen,clen;
char sendbuf[]="hello";
bzero(&saddr,sizeof(saddr));
serverfd=socket(AF_INET,SOCK_STREAM,0);
if(serverfd<0)
{
printf("can not create socket in server!\n");
return -1;
}
//bzero(&saddr,sizeof(saddr));
saddr.sin_family=AF_INET;
saddr.sin_port=htons(PORT);
saddr.sin_addr.s_addr=htonl(INADDR_ANY);
slen=sizeof(saddr);
bind(serverfd,(struct sockaddr* )&saddr,slen);
listen(serverfd,10);
printf("wait for connect!\n");
while(1)
{
clen=sizeof(caddr);
clientfd=accept(serverfd,(struct sockaddr*)&caddr,&clen);
//int se=send(clientfd,sendbuf,sizeof(sendbuf)+1,0);
// printf("\nSend message %d.\n",se);
printf("Server receive ing...\n");
memset(buf,0,30);
int re= recv(clientfd,buf,30,0);
if (re<0)
{
printf("Server receive failed!\n");
return -1;
}
else
printf("\n%d,",re);
//buf[strlen(buf)]='\0';
printf("%s",buf);
sleep(3);
close(clientfd);
}
//close(serverfd);
}
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <unistd.h>
#define MAX_BUF 50
#define PORT 8300
int main()
{
int sockfd,newsockfd;
int len;
struct sockaddr_in addr;
char cbuf[]="Client";
char rbuf[255];
int buflen;
bzero(&addr,sizeof(addr));
sockfd=socket(AF_INET,SOCK_STREAM,0);
addr.sin_family=AF_INET;
inet_pton(AF_INET,"127.0.0.1",&addr.sin_addr);
//addr.sin_addr.s_addr=htons(INADDR_ANY);
addr.sin_port=htons(PORT);
len=sizeof(addr);
newsockfd=connect(sockfd,(struct sockaddr*)&addr,len);
if(-1==newsockfd)
{
printf("connect failed!\n");
return -1;
}
//recv(sockfd,rbuf,255,0);
//printf("\n The receive message is:%s\n",rbuf);
//sleep(1);
buflen=strlen(cbuf);
printf("\n The Client message is:%d\n",buflen);
int se=send(sockfd,cbuf,buflen+1,0);
printf("Client Send message %d.\n",se);
sleep(3);
close(sockfd);
return 0;
}