1.main.cpp
#include <cassert>
#include <signal.h>
#include <thread>
#include <map>
#include <time.h>
#include <string>
#include "Server.h"
#pragma comment(lib,"Ws2_32.lib")
std::map<int, ServerSocket::Pointer> players;
void handlerRecvData(const ServerSocket::pointer& p,
const char* data,
int size) {
std::string info(data, data + size);
std::cout << "recv: " << info << std::endl;
for (int i = 0;i < 10;++i)
{
Sleep(1);
p->sendMessage("+<html>hello world</html>!");
}
}
int main(int argc,char** argv)
{
signal(SIGINT,signalHandler);
WSADATA data;
auto result = WSAStartup(MAKEWORD(2, 2), &data);
if (result != NO_ERROR)
{
std::cout << "error at WSAStartup\n";
return 1;
}
auto server = std::make_unique<Server>(8901);
if (!server) {
WSACleanup();
return 1;
}
server->socketRecv = handleRecvData;
server->socketClose = handleRemovePlayer;
auto clientIo = CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,0,0);
bool gameOver = false;
std::thread updateClientIo(
[clientIo, &gameOver] {updateClientIo(clientIo, gameOver);}
);
auto p = server.get();
handler = [p] {p->stop();};
WSACleanup();
return 0;
}
2.server.cpp
#include "Server.h"
#include <string>
#include <cassert>
Server::Server(u_short p)
:m_port(p),
m_listenSocket(INVALID_SOCKET),
m_completePort(NULL),
lpfnAcceptEx(nullptr),
m_currentAccetSocket(INVALID_SOCKET),
m_ioCompletePort(NULL),
m_running(false),m_acceptBuffer(1024){}
Server::~Server()
{
if (m_listenSocket != INVALID_SOCKET)
closesocket(m_listenSocket);
CloseHandle(m_ioCompletePort);
CloseHandle(m_completePort);
}
3.server.h
#ifndef YT_WIN_IOCP_SERVER_H
#define YT_WIN_IOCP_SERVER_H
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <mswsock.h>
#include <cstdio>
#include <iostream>
#include <vector>
#include <functional>
class Server {
public:
Server(u_short port);
~Server();
bool startAccept();
void waitingForAccept();
void waitingForIo();
bool isRunning()const { return m_running; }
void stop() { m_running = false; }
typedef std::function<void(ServerSocket::Pointer)> HandleNewConnect;
HandleNewConnect newConn;
ServerSocket::HandleRecvFunction socketRecv;
ServerSocket::HandleClose socketClose;
ServerSocket::HandleError socketErrro;
private:
u_short m_port;
SOCKET m_listenSocket;
HANDLE m_completePort;
LPFN_ACCEPTEX lpfnAcceptEx;
SOCKET m_currentAccetSocket;
WSAOVERLAPPED m_acceptUnit;
HANDLE m_ioCompletePort;
bool m_running;
std::vector<char> m_acceptBuffer;
bool tryNewConn();
};
#endif