#include#ifdef WIN32 #include #include #else #include #include #include #include #include #include #endif #include #ifdef WIN32 #pragma comment(lib, "ws2_32.lib") #endif class TcpThread { public: void Main() { char buf[1024] = { 0 }; while (1) { memset(buf, 0, 1024); int len1 = recv(client, buf, 1023, 0); printf("recv: %sn", buf); if (len1 <= 0) break; if (strstr(buf, "quit") != NULL) break; int sendlen = send(client, "ok", 3, 0); } #ifdef WIN32 closesocket(client); #else close(client); #endif delete this; } public: int client = 0; }; int main(int argc, char* argv[]) { #ifdef WIN32 WSADATA wsadata = { 0 }; WSAStartup(MAKEWORd(2, 2), &wsadata); #endif int s = socket(AF_INET, SOCK_STREAM, 0); printf("%d ", s); if (s == -1) { printf("Create socket failed.n"); return -1; } unsigned short port = 8080; if (argc > 1) { port = atoi(argv[1]); } sockaddr_in saddr; saddr.sin_family = AF_INET; saddr.sin_port = htons(port); saddr.sin_addr.s_addr = htonl(0); // 接受任意IP地址发送的数据 if (bind(s, (sockaddr*)&saddr, sizeof(saddr)) != 0) { printf("bind port %d failedn", port); return -2; } printf("bind port %d success!n", port); listen(s, 10); while (1) { sockaddr_in caddr = { 0 }; #ifdef WIN32 int len = sizeof(sockaddr_in); #else socklen_t len = sizeof(sockaddr_in); #endif int client = accept(s, (sockaddr*)&caddr, &len); if (client == -1) { printf("accpet failed.n"); return -3; } printf("accept socket:%dn", client); char *ip = inet_ntoa(caddr.sin_addr); printf("ip:%sn", ip); unsigned short cport = ntohs(caddr.sin_port); printf("port:%dn", cport); TcpThread *th = new TcpThread(); th->client = client; std::thread sth(&TcpThread::Main, th); sth.detach(); } #ifdef WIN32 closesocket(s); #else close(s); #endif #ifdef WIN32 WSACleanup(); #endif getchar(); return 0; }



