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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
|
#define WIN32_LEAN_AND_MEAN #define _WINSOCK_DEPRECATED_NO_WARNINGS #include <windows.h> #include <WinSock2.h> #include "iostream" #include "stdio.h" using namespace std;
enum CMD { CMD_LOGIN, CMD_LOGINOUT, CMD_ERROR }; struct DataHeader { short dataLength; short cmd; };
struct Login { char userName[32]; char PassWord[32]; }; struct LoginResult { char result[32]; }; struct LoginOut { char userName[32]; }; struct LoginOutResult { char result[32]; };
int main() { WORD ver = MAKEWORD(2, 2); WSADATA dat; WSAStartup(ver, &dat);
SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); char msgBuf[] = "Hello, I'm Server.";
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)); while (true) { DataHeader header = {}; int nLen = recv(_cSocket, (char*)&header, sizeof(DataHeader), 0); if (nLen <= 0) { printf("客户端已经退出, 任务结束。"); break; } printf("收到命令: %d 数据长度:%d\n", header.cmd, header.dataLength); switch (header.cmd) { case CMD_LOGIN: { Login login = {}; recv(_cSocket, (char*)&login, sizeof(login), 0); LoginResult ret = { "登录成功!!!"}; send(_cSocket, (char*)&header, sizeof(DataHeader), 0); send(_cSocket, (char*)&ret, sizeof(LoginResult), 0); } break; case CMD_LOGINOUT: { LoginOut loginout = {}; recv(_cSocket, (char*)&loginout, sizeof(LoginOut), 0); LoginOutResult ret = { "注销成功!!"}; send(_cSocket, (char*)&header, sizeof(DataHeader), 0); send(_cSocket, (char*)&ret, sizeof(LoginOutResult), 0); } break; default: header.cmd = CMD_ERROR; header.dataLength = 0; send(_cSocket, (char*)&header, sizeof(DataHeader), 0); break; } }
closesocket(_sock);
WSACleanup(); printf("已退出,任务结束"); getchar(); cout << "hello..." << endl; return 0; }
|