ListenServer.cpp
资源名称:GGBT.rar [点击查看]
上传用户:lds876
上传日期:2013-05-25
资源大小:567k
文件大小:2k
源码类别:
P2P编程
开发平台:
Visual C++
- // ListenServer.cpp: implementation of the CListenServer class.
- //
- //////////////////////////////////////////////////////////////////////
- #include "stdafx.h"
- #include "testbt.h"
- #include "ListenServer.h"
- #ifdef _DEBUG
- #undef THIS_FILE
- static char THIS_FILE[]=__FILE__;
- #define new DEBUG_NEW
- #endif
- //////////////////////////////////////////////////////////////////////
- // Construction/Destruction
- //////////////////////////////////////////////////////////////////////
- CListenServer::CListenServer()
- {
- m_hServer = INVALID_SOCKET;
- m_hevAccept = 0;
- m_hnewSocket = INVALID_SOCKET;
- }
- CListenServer::~CListenServer()
- {
- if (m_hServer)
- {
- closesocket(m_hServer);
- if (m_hevAccept)
- WaitForSingleObject(m_hevAccept, INFINITE);
- }
- }
- void CListenServer::StopListening()
- {
- }
- CListenServer::operator SOCKET()
- {
- return m_hServer;
- }
- long CListenServer::Bind(long lminport, long lmaxport)
- {
- SOCKET hserver = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, 0, WSA_FLAG_OVERLAPPED);
- if (hserver == INVALID_SOCKET)
- return false;
- long lport = 0;
- int iRet = -1;
- sockaddr_in addr = {0};
- addr.sin_family = AF_INET;
- for (lport=lminport; lport<=lmaxport; lport++)
- {
- addr.sin_port = lport;
- iRet = bind(hserver, (sockaddr*)&addr, sizeof(addr));
- if (iRet == 0)
- break;
- else
- {
- // string strErr = WSAShowError();
- // errorFunc("bind() server error:bind to port error: " + WSAShowError());
- }
- }
- if (iRet != 0)
- return false;
- iRet = listen(hserver, 10);
- if (iRet != 0)
- return false;
- m_hServer = hserver;
- return lport;
- }
- bool CListenServer::Accept(HANDLE hevAccept)
- {
- if (m_hevAccept || m_hServer == INVALID_SOCKET)
- {
- assert(false);
- return false;
- }
- m_hevAccept = hevAccept;
- DWORD dwThreadId = 0;
- ::CreateThread(0, 0, ListenProc, this, 0, &dwThreadId);
- TRACE("rnlisten thread = (%x)", dwThreadId);
- return true;
- }
- DWORD WINAPI CListenServer::ListenProc(void *pParam)
- {
- CListenServer* pListenServer = (CListenServer*) pParam;
- pListenServer->Listening();
- return 0;
- }
- void CListenServer::Listening()
- {
- CWinsockInit();
- sockaddr_in addr = {0};
- int iaddrlen = sizeof(addr);
- m_hnewSocket = WSAAccept(m_hServer, (sockaddr *)&addr, &iaddrlen, 0, 0);
- if (m_hnewSocket == INVALID_SOCKET)
- {
- string strErr = WSAShowError();
- }
- SetEvent(m_hevAccept);
- }
- SOCKET CListenServer::GetResult()
- {
- m_hevAccept = 0;
- return m_hnewSocket;
- }