当前位置: 技术问答>linux和unix
新手求助。。。关于最简单的服务器/客户端程序
来源: 互联网 发布时间:2016-12-28
本文导语: 下面是我写的服务器程序, 但是每次运行到时候就卡住不动了, 求各位大神指点 #include #include #include #include #include #include #include #include int main(int argc, char **argv) { int listenfd, connfd; socklen_t len; struc...
下面是我写的服务器程序, 但是每次运行到时候就卡住不动了, 求各位大神指点
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
int listenfd, connfd;
socklen_t len;
struct sockaddr_in servaddr, cliaddr;
char buff[255];
int n;
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
printf("error");}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family =AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(2000);
if(bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr))==-1)
{
perror("bind error");
exit(1);
}
printf("bind success");
if(listen(listenfd,10)==-1) {
perror("listen");
exit(1);
}
printf("server is run.../n");
while(1) {
len = sizeof(cliaddr);
if((connfd = accept(listenfd,(struct sockaddr *) &cliaddr,&len))==-1)
{
perror("accept");
exit(1);
}
//showClient(cliaddr);
if((n = recv(connfd,buff,sizeof(buff),0))==-1)
{
perror("recv");
exit(1);
}
buff[n]= '0';
printf("recieved %d bytes./n",n);
printf("the message is:%s/n",buff);
if(send(connfd,buff,strlen(buff),0)==-1)
perror("send");
close(connfd);
close(listenfd);
}
/*
struct sockaddr_in client_addr;
void showClient(struct sockaddr_in client_addr) {
printf("/nThe IP of client is:%s",inet_ntoa(client_addr.sin_addr));
printf("/nThe Port of client is:%d/n",ntohs(client_addr.sin_port));
}
*/
}
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char **argv)
{
int listenfd, connfd;
socklen_t len;
struct sockaddr_in servaddr, cliaddr;
char buff[255];
int n;
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
printf("error");}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family =AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(2000);
if(bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr))==-1)
{
perror("bind error");
exit(1);
}
printf("bind success");
if(listen(listenfd,10)==-1) {
perror("listen");
exit(1);
}
printf("server is run.../n");
while(1) {
len = sizeof(cliaddr);
if((connfd = accept(listenfd,(struct sockaddr *) &cliaddr,&len))==-1)
{
perror("accept");
exit(1);
}
//showClient(cliaddr);
if((n = recv(connfd,buff,sizeof(buff),0))==-1)
{
perror("recv");
exit(1);
}
buff[n]= '0';
printf("recieved %d bytes./n",n);
printf("the message is:%s/n",buff);
if(send(connfd,buff,strlen(buff),0)==-1)
perror("send");
close(connfd);
close(listenfd);
}
/*
struct sockaddr_in client_addr;
void showClient(struct sockaddr_in client_addr) {
printf("/nThe IP of client is:%s",inet_ntoa(client_addr.sin_addr));
printf("/nThe Port of client is:%d/n",ntohs(client_addr.sin_port));
}
*/
}
|
你的这个不是什么卡住不动的问题,而是你还要运行客户端才能执行.....你把客户端的发上来看看
|
accept挂起等待客服端连接