winsock select 学习代码(1)
标签:c class blog a tar int
// SelectCli.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
#pragma comment(lib,"ws2_32")
#define SOCKET_MAXCNT 64
#define THREAD_NUM 2 // 实验代码 与服务器配合 不可改变连接线程数
#define CONNECT_PORT 8773
#define CONNECT_ADDR "127.0.0.1"
DWORD WINAPI SocketFunc(LPVOID pM)
{
SOCKET sock;
char buf[100] = {0};
int result;
struct sockaddr_in cli_addr;
int num = *(int*)pM;
sock = socket(AF_INET,SOCK_STREAM,0);
cli_addr.sin_family = AF_INET;
cli_addr.sin_port = htons(CONNECT_PORT);
cli_addr.sin_addr.s_addr = inet_addr(CONNECT_ADDR);
result = connect(sock,(struct sockaddr*)&cli_addr,sizeof(cli_addr));
if(result == SOCKET_ERROR)
{
printf("%d thread: connect error\n",num);
exit(1);
}
while(1)
{
sprintf(buf,"%d thread: %s",num,"hello world!\n");
printf(buf);
result = send(sock,buf,100,0);
if(result == SOCKET_ERROR)
{
printf("2 ,%s\n","send error");
}
Sleep(3000);
}
exit(1);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int num[SOCKET_MAXCNT] = {0};
WSADATA wsa_data;
// 初始化数组 传递给线程 区别各个线程号
for(int i = 0 ;i
// SelectSrv.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include
#include
#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
学习了下 winsock 下的select写法
对于调用封装好的各类库 熟悉下原始写法还是很有裨益的
winsock select 学习代码(1),搜素材,soscw.com
winsock select 学习代码(1)
标签:c class blog a tar int
原文地址:http://www.cnblogs.com/itdef/p/3763300.html
评论