Windows操作系统提供了选择(select)、异步选择(WSAAsyncSelect)、事件选择(WSAEventSelect)、重叠I/O(Overlapped I/O)和完成端口(Completion Port)共五种I/O模型。每一种模型均使用于一种特定的应用场景。程序员应该对自己的应用需求非常明确,并且综合考虑到程序的拓展性和可移植性等因素,而选择不同的模式。
利用socket建立服务端和客户端之间通信。
服务端:
过程:WSAStartup——> socket —— >bind——>listen——>accept——>(read/write)——>close ——>WSAClearup
#include "stdafx.h"
#include "winsock2.h"
int _tmain(int argc, _TCHAR* argv[])
{
//int a;
WSADATA wsaData;
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
SOCKADDR_IN ClientAddr;
int Port = 5566;
//初始化windows socket2.2
WSAStartup(MAKEWORD(2,2), &wsaData);//2.2版本socket
//创建socket来连接客户端
ListeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//绑定地址,端口
bind(ListeningSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr));
// 开始监听客户端
listen(ListeningSocket, 5);//开始监听,指定最大连接数为5个
while(1)
{
// 等待客户端连接
NewConnection = accept(ListeningSocket, (SOCKADDR*)&ClientAddr, NULL);
if (NewConnection == SOCKET_ERROR)
{
continue;
}
///可以在这里实现与客户端之间通信
Sleep(5000);
break;
}
//关闭socket监听
closesocket(NewConnection);
closesocket(ListeningSocket);
WSACleanup();
return 0;
}
客户端
过程:WSAStartup——>socket ——>connect ——>read/write——>closesocket——>WSACleanup
#include "stdafx.h"
#include "winsock2.h"
int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsaData;
SOCKET clientsocket;
SOCKADDR_IN ServerAddr;
int Port = 5566;
WSAStartup(MAKEWORD(2, 2), &wsaData);
clientsocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_port = htons(Port);
ServerAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
connect(clientsocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr));
//与服务端之间进行通信
Sleep(5000);
closesocket(clientsocket);
WSACleanup();
return 0;
}
如果在编译时出现LNK2019的错误, 在link的Input中添加WS2_32.lib库文件即可解决。