首页 新闻 会员 周边 捐助

linux 多线程改windows sdk下的多线程出错

0
悬赏园豆:20 [待解决问题]

各位高手,我仿着下面这份代码尝试着去改成win32 SDK 的去。改了一天了了,但一直有问题。特来此求助、

/*
* Author: Huangx(C)
* Date: 2013/1/25
* Filename: server.c
*/

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <errno.h>
#include <strings.h>
#include <string.h>
#include <pthread.h>

#define USER_NUM 10
#define MAXBUF 1024
#define SERVER_PORT 10010

typedef struct typeInfo{
int socket_fd;
}typeInfo;

static int user[USER_NUM] = {0};

void *threadWrapper(void *info)
{
int new_fd;
fd_set rfds;
struct timeval tv;
char buf[MAXBUF];
int retval, maxfd = -1;
int len, i;
typeInfo *x = (typeInfo *)info;
int user_id = 0;

new_fd = x->socket_fd;

while (1)
{
FD_ZERO(&rfds);
FD_SET(new_fd, &rfds);

if (new_fd > maxfd)
maxfd = new_fd;

tv.tv_sec = 1;
tv.tv_usec = 0;
retval = select(maxfd + 1, &rfds, NULL, NULL, &tv);
if(retval < 0){
printf("select error? %s", strerror(errno));
close(new_fd);
break;
}
else if(retval == 0)
{
//printf("time out\n");
continue;
}
else
{
if (FD_ISSET(new_fd, &rfds)) {

bzero(buf, MAXBUF);

len = recv(new_fd, buf, MAXBUF, 0);
if (len > 0)
printf("Server:%s\n",buf);
else {
perror("recv failed");
break;
}
for(i = 0; i < USER_NUM; i++){
if(user[i] == new_fd){
user_id = i;
continue;
}
send(user[i], buf, len, 0);
}
}
}

}
close(new_fd);
user[user_id] = 0;
printf("(fd:%d) out\n", new_fd);
}

void createThread(void *info)
{
pthread_t tid;
pthread_attr_t attr;

pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&tid, &attr, threadWrapper, (void *)info);
pthread_attr_destroy(&attr);

}

int main(int argc, char **argv)
{
int sock_fd, new_fd;
socklen_t len;
struct sockaddr_in my_addr, their_addr;
typeInfo in;
int i;
int opt = 1;


if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
return -1;
}

bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(SERVER_PORT);
my_addr.sin_addr.s_addr = INADDR_ANY;

setsockopt(sock_fd, SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));

if (bind(sock_fd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr))== -1) {
perror("socket bind");
return -1;
}

if (listen(sock_fd, USER_NUM) == -1) {
perror("socket listen");
return -1;
}

while(1)
{

printf("waiting ...\n");
len = sizeof(struct sockaddr);
if((new_fd = accept(sock_fd, (struct sockaddr *) &their_addr,&len)) == -1){
perror("socket accept");
return -1;
}
else{
printf("Connection from %s, Port %d, Socket fd %d\n",\
inet_ntoa(their_addr.sin_addr),ntohs(their_addr.sin_port), new_fd);
in.socket_fd = new_fd;
for(i=0;i<USER_NUM;i++){
if(user[i] == 0){
user[i] = new_fd;
break;
}
}
createThread((void *)&in);
}

}

return 0;
}

线木偶的主页 线木偶 | 初学一级 | 园豆:8
提问于:2013-04-23 19:37
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册