1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
| #define WIN32_LEAN_AND_MEAN #define _WINSOCK_DEPRECATED_NO_WARNINGS #include <windows.h> #include <WinSock2.h> #include "iostream" #include "stdio.h" using namespace std;
int main() {
WORD ver = MAKEWORD(2, 2);
WSADATA dat; WSAStartup(ver, &dat);
SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in _sin = {}; _sin.sin_family = AF_INET; _sin.sin_port = htons(4567); _sin.sin_addr.S_un.S_addr = INADDR_ANY; if (SOCKET_ERROR == bind(_sock, (sockaddr*)&_sin, sizeof(_sin))) { printf("错误,绑定网络端口失败...\n"); } else { printf("绑定端口成功...\n"); }
if (SOCKET_ERROR == listen(_sock, 5)) { printf("错误,监听网络端口失败...\n"); } else { printf("监听网络端口成功...\n"); }
sockaddr_in clientAddr = {}; int nAddrLen = sizeof(sockaddr_in); SOCKET _cSocket = INVALID_SOCKET; _cSocket = accept(_sock, (sockaddr*)&clientAddr, &nAddrLen); if (INVALID_SOCKET == _cSocket) { printf("错误,接收到无效客户端SOCKET...\n"); } printf("新客户端加入: socket = %d IP = %s \n", _cSocket, inet_ntoa(clientAddr.sin_addr)); char _recvBuf[128] = {}; while (true) {
int nLen = recv(_cSocket, _recvBuf, 128, 0); if (nLen <= 0) { printf("客户端已经退出, 任务结束。"); break; } printf("收到命令: %s\n", _recvBuf); if (0 == strcmp(_recvBuf, "getname")) { char msgBuf[] = "无所不能的小鑫!"; send(_cSocket, msgBuf, strlen(msgBuf) + 1, 0); } else if(0 == strcmp(_recvBuf, "getage")) { char msgBuf[] = "23"; send(_cSocket, msgBuf, strlen(msgBuf) + 1, 0); } else { char msgBuf[] = "你个傻狗!!输入错了"; send(_cSocket, msgBuf, strlen(msgBuf) + 1, 0); } }
closesocket(_sock);
WSACleanup(); printf("已退出,任务结束"); getchar(); cout << "hello..." << endl; return 0; }
|