sockets - c++ winsock - server communicates only with single client while it should communicate with every client -
i writing single chat program gui. wanted write server accept many clients. every client can connect successfuly. there strange problem sending , receiving data. use select() , thread handle many sockets @ same time. if client sends data server, receive , send client (the client written without "prediction"). server won't send further clients (like every client had own private conversation server). here's code:
// rewritten beej's tutorial little , insignificant changes /* in thread */ fd_set mainfd; fd_set readfd; // sin-size, newfd, maxfd - int while(true) { readfd = mainfd; if(select(maxfd+1, &readfd, null, null, null) == -1) { messageboxa(null, "error while trying accept incoming connections (select)", "error", 16); itoa(getlasterror(), buf, 10); messageboxa(null, buf, buf, 0); break; } for(int = 0; <= maxfd; i++) { char* psr; char srmsg[256]; if(fd_isset(i, &readfd)) { if(i == mainsocket) { sin_size = sizeof(their_addr); newfd = accept(mainsocket, (struct sockaddr*)&their_addr, &sin_size); if(newfd == socket_error) { addtexttoedit(hstaticchat, "* error: couldn't accept incoming connection.", true); } else { fd_set(newfd, &mainfd); if(newfd > maxfd) { maxfd = newfd; } } } else { len = recv(i, srmsg, 256, 0); if(len == 0 || len == socket_error) { addtexttoedit(hstaticchat, "* client has disconnected", true); close(i); fd_clr(i, &mainfd); } else { addtexttoedit(hstaticchat, srmsg, true); for(int j = 0; j <= maxfd; j++) { if(fd_isset(j, &readfd)) { send(j, srmsg, len, 0); } } } } } } }
you sending data clients whos fd in readfd
, is, 1 communicated you. try test fd_isset(j, mainfd)
instead.
Comments
Post a Comment