//包頭
struct dataheader
;//包體
struct login:public dataheader
char username[32];
char password[32];
};struct loginresult :public dataheader
int result;
};struct logout :public dataheader
char username[32];
};struct logoutresult :public dataheader
int result;
};std::vector g_client;
int process_solve(socket _csock)
;//5.接收客戶端新資料
int nlen = recv(_csock, szrecv, sizeof(dataheader), 0);
dataheader header = (dataheader)szrecv;
if (nlen <= 0)
switch (header->cmd)
case cmd_logout:
break;
default:
; send(_csock, (char *)&header.cmd, sizeof(header), 0);
} break;
}
int main()
//2.繫結
sockaddr_in _sin = {}; //建立網路位址
_sin.sin_family = af_inet;
_sin.sin_port = htons(4567); //host to network short
_sin.sin_addr.s_un.s_addr = inet_addr("127.0.0.1"); // ip位址
if (bind(_sock, (sockaddr *)&_sin, sizeof(_sin)) == socket_error)
else
//3.監聽網路埠
if (listen(_sock, 5) == socket_error)//第二個引數為最大等待多少人可以同時連線
else
while (1)
/*select(
_in_ int nfds,
_inout_opt_ fd_set far * readfds,
_inout_opt_ fd_set far * writefds,
_inout_opt_ fd_set far * exceptfds,
_in_opt_ const struct timeval far * timeout
);*/
//nfds是乙個整數值,是指fd_set集合所有的描述符(select裡的第乙個引數)的範圍(而不是數量)
//既是所有檔案描述符最大值+1
int ret = select(_sock + 1, &fd_read, &fd_write, &fd_exp, null);
if (ret < 0)
if (fd_isset(_sock, &fd_read))
;int naddrlen = sizeof(sockaddr_in);
socket _csock = invalid_socket;
_csock = accept(_sock, (sockaddr *)&clientaddr, &naddrlen);
if (_csock == invalid_socket)
g_client.push_back(_csock);
printf("新客戶端加入:socket=%d,ip = %s\n", (int)_csock, inet_ntoa(clientaddr.sin_addr));//inet_ntoa(clientaddr.sin_addr)將接收到的ip位址轉化為字串
}for (int n = 0; n < fd_read.fd_count; n++)}}
}for (int n = g_client.size(); n >= 0; n--)
//8.關閉自身的socket
closesocket(_sock);
//winsocket關閉
wsacleanup();
system("pause");
return 0;
winsock select服務端模型
include stdafx.h include include pragma comment lib,ws2 32.lib void initsocket confirm that the winsock dll supports 2.2.note that if the dll supports...
完成埠模型服務端
windows 完成埠模型服務端 include include pragma comment lib,ws2 32.lib using namespace std const int serverport 4399 const int msgsize 1024 typedef enum opera...
HTTP服務端JSON服務端
最後更新日期 2014 5 18 author kagula 內容簡介 cppcms是個開源web開發框架,通過它可以很容易實現http服務和json服務,這裡介紹cppcms開發環境的搭建。寫乙個cppcms測試程式,它建立http服務,向瀏覽器返回hello,world頁面。cppcms依賴的一...