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 ... "); 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 ... "); continue; } printf("socket:%d ip:%s port:%d join ... ", 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 ... "); FD_CLR(skt, &fds);//将客户端在集合中清除 closesocket(skt);//关闭客户端socket continue; } if (iret == 0) {//客户端退出 printf("[client] exit ... "); FD_CLR(skt, &fds);//将客户端在集合中清除 closesocket(skt);//关闭客户端socket continue; } printf("[client] msg: %s ", 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 ... "); 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("************************* "); printf("*getName * "); printf("*getAge * "); printf("*exit * "); printf("************************* "); 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 ... "); return -1; } printf("[client] %s send success ... ", buf); iret = recv(sktCli, buf, sizeof(buf), 0); if (iret == SOCKET_ERROR) { printf("[client] recv error ... "); return -1; } if (iret == 0) { printf("[client] server exit ... "); return -1; } printf("[server] msg: %s ", buf); } destroy(sktCli); return 0; }