主要代码
#pragma once
#include "pre.h"
#include <thread>
NAMESPACE(DEF)
class Socket {
public:
Socket() :s_(INVALID_SOCKET){}
~Socket() {
if(INVALID_SOCKET != s_)
closesocket(s_);
s_ = INVALID_SOCKET;
}
bool Init(SOCKET& s) {
s_ = s;
s = INVALID_SOCKET;
return true;
}
bool Init(SOCKET&& s) {
s_ = s;
s = INVALID_SOCKET;
return true;
}
bool Init() {
s_ = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == s_)
return false;
return true;
}
void Reset() {
s_ = INVALID_SOCKET;
}
Socket(Socket& s) {
s_ = s.getsock();
s.Reset();
}
SOCKET getsock() { return s_; }
private:
const Socket& operator=(const Socket& s);
SOCKET s_;
};
class SockManager {
public:
bool StartListen() {
Socket s;
if (!s.Init())
return false;
if (bind(s.getsock(), (LPSOCKADDR)&serv_, sizeof(serv_)) == SOCKET_ERROR){
std::cerr<<"bind()failed: "<<WSAGetLastError()<<std::endl;
return false;
}
if (listen(s.getsock(), 5) == SOCKET_ERROR){
std::cerr << "listen()failed: " << WSAGetLastError() << std::endl;
return false;
}
struct sockaddr_in cliet;
int iLen = sizeof(cliet);
while (1) {
Socket rs;
rs.Init( accept(s.getsock(),(struct sockaddr*)&cliet,&iLen) );
if (INVALID_SOCKET == rs.getsock()) {
std::cerr << "accept() failed: " << WSAGetLastError() << std::endl;
return false;
}
std::cout << "accepted client IP :[" << inet_ntoa(cliet.sin_addr) << "],port:[" <<
ntohs(cliet.sin_port) << "]\n";
std::thread (&SockManager::SockHandleThread,this, rs).detach();
}
return true;
}
SockManager(int port = 9999) :port_(port) {
serv_.sin_family = AF_INET;
serv_.sin_port = htons(port_);
serv_.sin_addr.s_addr = htonl(INADDR_ANY);
}
private:
bool ServerStatic(Socket&, char*, long);
void SockHandleThread(Socket s);
int port_;
struct sockaddr_in serv_;
};
ENDNAMESPACE(DEF)
参考
《深入理解计算机系统》