当前位置: 技术问答>linux和unix
菜鸟求助多线程并发服务器
来源: 互联网 发布时间:2016-12-10
本文导语: 本人菜鸟,刚刚看过unix网络编程,试着写了一个简单的多线程的并发服务器,可是只能给客户端发送信息,却接收不到客户端发给服务器的信息,用netstat -t 发现,程序的接收队列里有数据,但程序却没接收到,还...
本人菜鸟,刚刚看过unix网络编程,试着写了一个简单的多线程的并发服务器,可是只能给客户端发送信息,却接收不到客户端发给服务器的信息,用netstat -t 发现,程序的接收队列里有数据,但程序却没接收到,还请高手帮忙
程序如下
程序如下
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
//#include "lookup3.h"
#include "my.h"
#define PORT 6800
#define BUFSIZE 255
void *chat(int *clifd);
struct user usr[59];
int main(int argc, char **argv)
{
int servfd, clifd;
struct sockaddr_in servaddr, cliaddr;
pthread_t thread;
pthread_attr_t thread_attr;
char buffer[BUFSIZE];
int ret, len;
long hashvalue;
int opt = SO_REUSEADDR;
servfd = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(servfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
bzero(&servaddr, sizeof(cliaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(servfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
if(ret == -1) {
printf("bind failed.n");
exit(-1);
}
ret = listen(servfd, 10);
if(ret == -1){
printf("listen error!n");
exit(-1);
}
printf("server is waiting here...n");
len = sizeof(cliaddr);
while(1){
clifd = accept(servfd, (struct sockaddr *)&cliaddr, &len);
if(clifd == -1){
printf("accept failed.n");
break;
}
memset(buffer, 0, BUFSIZE);
printf("connect from: %s,%dn", inet_ntop(AF_INET, &cliaddr.sin_addr, buffer,BUFSIZE), ntohs(cliaddr.sin_port));
// pthread_attr_init(&thread_attr);
// pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
ret = pthread_create(&thread, NULL, chat, &clifd);
if(ret == -1){
printf("create chat thread failed.n");
close(clifd);
break;
}
}
close(servfd);
}
void *chat(int *clifd){
fd_set rset;
int sockfd, maxfd;
char buffer[BUFSIZE]; //鎺ユ敹锛?鍙戦€佺紦鍐插尯
int ret;
printf("thread created.n");
sockfd = *clifd;
FD_ZERO(&rset);
maxfd = sockfd>fileno(stdin)?sockfd:fileno(stdin) + 1;
while(1){
FD_SET(sockfd, &rset);
FD_SET(fileno(stdin), &rset);
ret = select(maxfd, &rset, NULL, NULL, NULL);
if(ret == -1){
printf("select failed in sockfd: %dn", sockfd);
close(sockfd);
pthread_exit((void *)(-1));
}
if(FD_ISSET(fileno(stdin), &rset)){
bzero(buffer, BUFSIZE);
fgets(buffer, BUFSIZE, stdin);
ret = send(sockfd, buffer, strlen(buffer), 0);
if(ret == -1){
printf("send failed.n");
}
}
if(FD_ISSET(sockfd, &rset)){
memset(buffer, 0, BUFSIZE);
ret = read(sockfd, buffer, BUFSIZE);
if(ret == -1){
printf("recv failed.n");
}
else if(ret == 0){
printf("the other side shut down.n");
close(sockfd);
pthread_exit((void *)1);
}
else
printf("client: %sn", buffer);
}
}
}
|
maxfd = sockfd>fileno(stdin)?sockfd:fileno(stdin) + 1;
该为:
maxfd = sockfd>fileno(stdin)?sockfd+1:fileno(stdin) + 1;
试试
该为:
maxfd = sockfd>fileno(stdin)?sockfd+1:fileno(stdin) + 1;
试试
|
1个客户端的情况下也是这样吗
把FD_ZERO(&rset); 放在循环里面呢?
把FD_ZERO(&rset); 放在循环里面呢?