LRESULT KPortServer::Run() { bool bE = false; WSADATA wsData; #define BUF_LEN 20 char szMsgBuf[BUF_LEN + 1]; sockaddr_in addrClient; SYSTEMTIME sysTime; bool bResult = true; WSAStartup(MAKEWORD(2, 2), &wsData); KServer::Init(); KServer::ResetSocket(); fprintf(stdout, "Waitting for client:/n"); while (true) { SOCKET skClient = INVALID_SOCKET; PROCESS_ERROR(INVALID_SOCKET != (skClient = StartAccepting())); addrClient = GetClientAddress(); GetLocalTime(&sysTime); sprintf(szMsgBuf, "%d/0", ntohs(addrClient.sin_port)); send(skClient, szMsgBuf, strlen(szMsgBuf), !MSG_DONTROUTE); fprintf(stdout, "%d:%d:%d:%d/tClient %s %d connected!/n", sysTime.wHour, sysTime.wMinute, sysTime.wSecond, sysTime.wMilliseconds, inet_ntoa(addrClient.sin_addr), ntohs(addrClient.sin_port)); printf("%s:/tSocket closed!/n", ::GetSystemTimeAsString()); shutdown(skClient, SD_RECEIVE); closesocket(skClient); } bE = true; Exit0: WSACleanup(); return bE; #undef BUF_LEN }
1 条评论
您还未登录,请先
登录
后发表或查看评论
1 条评论
-
net_keyer 2008.05.26/******************************************************************************* * @Name : CreateSocketWithGlobalPort * @brief : 创建一个socket,该socket将被绑定到一个本地端口,同时会预测用该socket连接网络后的全局端口 * @return : bool 返回是否创建成功 * @param : SOCKET *sktOut 返回被创建的socket * @param : unsigned short *nLocalPort 本地端口,如果为NULL则将自动分配一个 * @param : unsigned short *nGlobalPort 返回预测到的全局端口 * @param : int nDelta NAT类型 * @param : sockaddr_in addSTUNT STUNT服务器地址 * @remark : 是用该函数后应该尽快使用其连接到外网,以免端口被其它进程占用 *******************************************************************************/ bool CreateSocketWithGlobalPort(SOCKET *sktOut, unsigned short *nLocalPort, unsigned short *nGlobalPort, int nDelta) { #define MAX_BUF_LEN 20 VERIFY(NULL != sktOut && NULL != nLocalPort && NULL != nGlobalPort); bool bOpt = true; bool bE = false; int nRead = 0; int nLen = sizeof sockaddr_in; char szBuf[MAX_BUF_LEN + 1]; SOCKET skt; sockaddr_in addLocal; sockaddr_in addSTUNT; ::CreateInetAddr(&addSTUNT, STUNTSERVER_IP1, STUNT_PORT); RETURN_ON_FAIL(INVALID_SOCKET != (skt = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP))); setsockopt(skt, SOL_SOCKET, SO_REUSEADDR, (const char*)&bOpt, sizeof bOpt); if (nLocalPort != 0) //指定端口 { MAKESURE(::CreateInetAddr(&addLocal, INADDR_ANY, *nLocalPort)); bind(skt, (sockaddr*)&





