// SelectSrv.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <winsock2.h>
#include <conio.h>
#pragma comment(lib,"ws2_32")
#define SOCKET_MAXCNT 64
#define CONNECT_PORT 8773
#define CONNECT_ADDR "127.0.0.1"
int
_tmain( int
argc, _TCHAR* argv[])
{
WSADATA wsa_data;
fd_set read_all;
SOCKET srv_listen = INVALID_SOCKET;
struct
sockaddr_in srv_addr;
int
result,ready_cnt;
int
addr_len = sizeof (srv_addr);
SOCKET recv_sock[2] = {INVALID_SOCKET,INVALID_SOCKET};
WSAStartup(MAKEWORD(2,2),&wsa_data);
srv_listen = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(CONNECT_PORT);
srv_addr.sin_addr.s_addr = INADDR_ANY;
result = bind(srv_listen,( struct
sockaddr*)&srv_addr,addr_len);
if (result == SOCKET_ERROR)
{
perror( "err " );
printf( "line %d \n" ,__LINE__);
return
-1;
}
listen(srv_listen,SOMAXCONN);
FD_ZERO(&read_all);
FD_SET(srv_listen,&read_all);
fd_set read_set;
while (1)
{
read_set = read_all;
ready_cnt = select (0,&read_set,NULL,NULL,NULL);
if (ready_cnt == SOCKET_ERROR)
{
perror( "err " );
printf( "line %d \n" ,__LINE__);
return
-1;
}
if (FD_ISSET(srv_listen,&read_set))
{
struct
sockaddr_in faddr;
int
addr_len = sizeof (faddr);
static
int sock_num = 0;
if (sock_num > 1)
{
perror( "connect socket is too much\n " );
printf( "line %d \n" ,__LINE__);
return
-1;
}
recv_sock[sock_num] = accept(srv_listen,( struct
sockaddr*)&faddr,&addr_len);
if (recv_sock[sock_num] == INVALID_SOCKET)
{
perror( "err " );
printf( "line %d \n" ,__LINE__);
return
-1;
}
FD_SET(recv_sock[sock_num],&read_all);
sock_num++;
continue ;
}
for ( int
i = 0 ; i < 2;i++)
{
char
buf[100] = {0};
if (!FD_ISSET(recv_sock[i],&read_set))
{
continue ;
}
result = recv(recv_sock[i],buf,100,NULL);
if (result != SOCKET_ERROR)
{
printf( "recv thread .%s\n" ,buf);
}
}
}
getch();
return
0;
}
|