- 论坛徽章:
- 0
|
目的:
建立一个tcp server,使用select多路复用处理用户新建连接以及以及建立的连接的数据读操作
思路:
1.建立server socket
2.把server socket加入select的读数组
3.客户端建立的连接加入select的读数组
4.处理新的连接以及以及建立的连接的数据
代码:
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netinet/in.h> // struct sockaddr_in
#include <sys/select.h> // select()
#define SERVER_PORT 3361
#define BUFF_SIZE 512
#define MAX_TCP_CONNECTION 10
int main()
{
int ServerFd, ClientFd[MAX_TCP_CONNECTION];
int ClientAddrLen, Bytes, MaxClientIndex=0, i;
struct sockaddr_in ServerAddr, ClientAddr;
char Buf[BUFF_SIZE];
fd_set readset;
ServerFd = socket(AF_INET, SOCK_STREAM, 0);
memset(&ServerAddr, 0, sizeof(struct sockaddr_in));
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(SERVER_PORT);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
bind (ServerFd, (struct sockaddr*)&ServerAddr, sizeof(struct sockaddr));
listen(ServerFd, 5);
while(1)
{
FD_ZERO(&readset);
FD_SET(ServerFd, &readset);
for(i=0;i<MaxClientIndex;i++)
FD_SET(ClientFd[i], &readset);
if (MaxClientIndex)
select(ClientFd[MaxClientIndex]+1, &readset, NULL, NULL, NULL);
else
select(ServerFd+1, &readset, NULL, NULL, NULL);
if (FD_ISSET(ServerFd, &readset))
{
ClientFd[MaxClientIndex] = accept(ServerFd, (struct sockaddr*)&ClientAddr, &ClientAddrLen);
printf("Ah, new connection < %d 0x%.8x:%d > established!\n", ClientFd[MaxClientIndex], ClientAddr.sin_addr.s_addr, ClientAddr.sin_port);
MaxClientIndex++;
printf("MAX Connection: %d\n", MaxClientIndex);
}
else
{
for(i=0;i<MaxClientIndex;i++)
{
if (!FD_ISSET(ClientFd[i], &readset))
continue;
Bytes = read(ClientFd[i], Buf, BUFF_SIZE-1);
if (Bytes<=0)
continue;
Buf[Bytes] = '\0';
printf("CONNECTION(%d) %s", ClientFd[i], Buf);
}
}
}
close(ServerFd);
return 0;
}
|
现象:
客户端可以建立到服务器的连接,但是以及建立连接的客户端发送的数据服务器端收不到,使用gdb调试发现阻塞在select调用没有返回。
问题:
如何处理accept还要处理read操作,谢谢。 |
|