server
//socket 使用select模型 连接多个客户端 int function05() { SOCKET sktServ = init("0.0.0.0", 8080); if (sktServ == INVALID_SOCKET) { return -1; } fd_set fds; FD_ZERO(&fds);//清空集合 FD_SET(sktServ, &fds);//将服务器socket放入集合 timeval tv = {0, 300}; while (true) { fd_set readfds = fds;//初始化监听的集合 int iret = select(0, &readfds, NULL, NULL, &tv); if (iret < 0) { printf("[server] select error ...\n"); break; } if (iret == 0) {//集合中套接字没有响应的 continue; } for (u_int i = 0; i < readfds.fd_count; ++i) { SOCKET skt = readfds.fd_array[i]; if (skt == sktServ) {//有新的客户端请求连接 sockaddr_in addr = {0}; int addrlen = sizeof(addr); SOCKET sktCli = accept(skt, (sockaddr *)&addr, &addrlen); if (sktCli == INVALID_SOCKET) { printf("[server] accept error ...\n"); continue; } printf("socket:%d ip:%s port:%d join ...\n", sktCli, inet_ntoa(addr.sin_addr), ntohs(addr.sin_port)); FD_SET(sktCli, &fds);//将新连接的客户端放入集合 continue; } //客户端响应请求 char buf[1024] = {0}; iret = recv(skt, buf, sizeof(buf), 0); if (iret == SOCKET_ERROR) {//接受错误 printf("[server] recv error ...\n"); FD_CLR(skt, &fds);//将客户端在集合中清除 closesocket(skt);//关闭客户端socket continue; } if (iret == 0) {//客户端退出 printf("[client] exit ...\n"); FD_CLR(skt, &fds);//将客户端在集合中清除 closesocket(skt);//关闭客户端socket continue; } printf("[client] msg: %s\n", buf); if (strcmp(buf, "getName") == 0) { sprintf(buf, "%s", "爱白菜的小昆虫."); } else if (strcmp(buf, "getAge") == 0) { sprintf(buf, "%s", "100000."); } else { sprintf(buf, "%s", "????."); } send(skt, buf, strlen(buf) + 1, 0); } } printf("[server] exit ...\n"); FD_CLR(sktServ, &fds);//清除集合中的服务器socket destroy(sktServ); return 0; }
client
//socket简单的客户端代码 int function05() { SOCKET sktCli = init("192.168.3.18", 8080); if (sktCli == INVALID_SOCKET) { return -1; } char buf[1024]; while (true) { printf("*************************\n"); printf("*getName *\n"); printf("*getAge *\n"); printf("*exit *\n"); printf("*************************\n"); scanf("%s", buf); if (strcmp(buf, "exit") == 0) { break; } int iret = send(sktCli, buf, strlen(buf) + 1, 0); if (iret == SOCKET_ERROR) { printf("[client] send error ...\n"); return -1; } printf("[client] %s send success ...\n", buf); iret = recv(sktCli, buf, sizeof(buf), 0); if (iret == SOCKET_ERROR) { printf("[client] recv error ...\n"); return -1; } if (iret == 0) { printf("[client] server exit ...\n"); return -1; } printf("[server] msg: %s\n", buf); } destroy(sktCli); return 0; }