@
Wirbelwind 这是服务端代码
void server() {
if ((this->sock_fd_ = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
errno_abort("craete socket failed.");
}
if (setsockopt(this->sock_fd_, SOL_SOCKET, SO_BROADCAST, &this->true_flag_, sizeof(this->true_flag_)) < 0) {
errno_abort("set socket opt failed.");
}
memset(&this->send_addr, 0, sizeof(this->send_addr));
send_addr.sin_family = AF_INET;
send_addr.sin_port = (in_port_t) htons(this->server_port_);
inet_aton(this->address_, &send_addr.sin_addr);
while (this->running_) {
if (this->queue_->size() <= 0) continue;
char buf[this->msg_size_];
auto msg = this->queue_->pop();
int retry = 0;
while (retry < this->max_retry_) {
snprintf(buf, sizeof(buf), "%s", msg->c_str());
if (sendto(this->sock_fd_, buf, strlen(buf) + 1, 0,
(struct sockaddr *) &this->send_addr, sizeof(this->send_addr)) >= 0) {
retry = 0;
break;
}
printf("\033[1;91m message %s send failed, retry(%d).\033[0m\n", msg->c_str(), retry);
retry++;
}
if (retry != 0) {
printf("\033[1;91m message %s send finally failed.\033[0m\n", msg->c_str());
}
// 200 毫秒
usleep(10000000 / 5);
}
}