Use non-blocking sockets whenever possible
int flags, S;
Flags = FCNTL (FD, F_GETFL, 0);
if (flags = =-1) {
Close (FD);
return-1;
}
Flags |= O_nonblock;
s = fcntl (FD, F_SETFL, flags);
if (s = =-1) {
Close (FD);
return-1;
}
Get In/out events on multiple sockets using an efficient epoll mechanism
-
A non-blocking socket connection server is not necessarily immediately connected to the servers
for further tracking by judging the return value and error number of the Connect function
INT ret =:: Connect (THIS->FD, ( struct sockaddr*) & (SERVER_ADDR), sizeof (SERVER_ADDR));
if (ret = = 0) {
& nbsp; this->on_connected ();
}else if (Ret < 0 && errno! = einprogress) {
& nbsp; //error
}else{
on_connecting ();
}
-
In/out event If connecting needs to determine the socket status, the socket reset will also generate an event before entering a valid read and write
if (this->connect_ Status = = 1) {//connecting
int status = 0;
socklen_t Slen;
if (getsockopt (THIS->FD, Sol_socket, So_error, (void*) &status, & Slen) < 0) {
this->on_epollhup ();
return;
}
if (status! = 0) {
this->on_epollhup ();
return;
}
on_connected ();
}
-
Read-write error, error code to determine whether it is an error or the data read or the buffer is full, an error occurs according to the socket disconnect
Error codes include: Sigpip, Eagain, etc., eagain means reading or buffer full, Wait for the next event handler to read or write
-
In order to achieve higher performance, Epoll uses the Epollet (edge trigger) mechanism, but when an event occurs, when there is no data to write, the next time there is an out-of-date
will not have an out event, so you can record a write-idling identity write_nil_loop, Epoll_wait event before determining if there is data sent and occurs Write_nil_loop, if any, re-enlist Epoll event
if (Worker->is_write_nil_loop () && (Events & Epollout)) {
epoll->remove (worker);
epoll->add ( Worker, events);
}else if (worker->get_events_mask ()! = events) {
Epoll->modify (worker, events);
}
Also, when reading the data, read the data as much as possible until the recv return value -1,errno== eagain, and other errors follow error handling
Periodic summary of asynchronous RPC under Linux-non-blocking socket client