#include #include #include #include #include #define CLIENT_SIZE 32 SOCKET sfd; SOCKET cfds[CLIENT_SIZE]; void send_the_message(int sock, const char *Buff, int szBuf) { char Buf[2048] = {0}; int tempsock; sprintf(Buf, ":", sock); strcat(Buf, Buff); for(int i = 0; i < CLIENT_SIZE; i++) { if(cfds[i] != 0 && cfds[i] != sock) { tempsock = cfds[i]; send(tempsock, Buf, strlen(Buf)+1, 0); } } } void receive_message(void* param) { int res; char Buf[1024] = {0}; int sock = *((SOCKET*)param); free(param); printf("recv start %d\n", sock); while(1) { res = recv(sock, Buf, sizeof(Buf), 0); if(res == -1 || res > sizeof(Buf) || res == 0) { #if WIN_PART printf("\n", GetLastError()); #elif LINUX_PART perror("recv error"); #endif break; } printf("recv buf:%d,%s",res, Buf); send_the_message(sock, Buf, strlen(Buf)+1); } printf(" exit\n", sock); for(int i = 0; i < CLIENT_SIZE; i++) { if(cfds[i] == sock) { cfds[i] = 0; } } } void acceptfunc(void* param) { char *ip; unsigned short port; SOCKET* psock; SOCKET sock; while(1) { psock = (SOCKET*)malloc(sizeof(SOCKET)); if(psock == NULL) { exit(-1); } if (sock_accpet(sfd, &sock, &ip, &port) != 0) { continue; } *psock = sock; for(int i = 0; i < CLIENT_SIZE; i++) { if(cfds[i] == 0) { cfds[i] = sock; printf("\n", ip, port, sock); free(ip); thread_create(NULL, receive_message, (void*)psock); goto CONTINUE; } } printf("client full"); exit(-2); CONTINUE: psock = NULL; } } int main() { char Buf[128]; int res = make_server_sock(&sfd, _SOCKET_TEST_IP6, _SOCKET_TEST_PORT); if(res != 0) { printf("server start error\npress enter to continue"); getchar(); return 0; } printf("server start...\n"); thread_create(NULL, acceptfunc, NULL); while(1) { fgets(Buf, sizeof(Buf), stdin); printf("%s", Buf); if(strncasecmp(Buf, "exit", strlen("exit")) == 0) { printf("exit success\npress enter to continue"); getchar(); exit(-1); } } return 0; }