Use Select in examples
This commit is contained in:
committed by
Keith Winstein
parent
2112a3865c
commit
043f9af260
+13
-17
@@ -18,11 +18,11 @@
|
||||
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/poll.h>
|
||||
|
||||
#include "user.h"
|
||||
#include "fatal_assert.h"
|
||||
#include "networktransport.cc"
|
||||
#include "select.h"
|
||||
|
||||
using namespace Network;
|
||||
|
||||
@@ -58,20 +58,19 @@ int main( int argc, char *argv[] )
|
||||
fprintf( stderr, "Port bound is %d, key is %s\n", n->port(), n->get_key().c_str() );
|
||||
|
||||
if ( server ) {
|
||||
struct pollfd my_pollfd;
|
||||
my_pollfd.fd = n->fd();
|
||||
my_pollfd.events = POLLIN;
|
||||
Select sel;
|
||||
sel.add_fd( n->fd() );
|
||||
uint64_t last_num = n->get_remote_state_num();
|
||||
while ( true ) {
|
||||
try {
|
||||
if ( poll( &my_pollfd, 1, n->wait_time() ) < 0 ) {
|
||||
perror( "poll" );
|
||||
if ( sel.select( n->wait_time() ) < 0 ) {
|
||||
perror( "select" );
|
||||
exit( 1 );
|
||||
}
|
||||
|
||||
n->tick();
|
||||
|
||||
if ( my_pollfd.revents & POLLIN ) {
|
||||
if ( sel.read( n->fd() ) ) {
|
||||
n->recv();
|
||||
|
||||
if ( n->get_remote_state_num() != last_num ) {
|
||||
@@ -101,28 +100,25 @@ int main( int argc, char *argv[] )
|
||||
exit( 1 );
|
||||
}
|
||||
|
||||
struct pollfd fds[ 2 ];
|
||||
fds[ 0 ].fd = STDIN_FILENO;
|
||||
fds[ 0 ].events = POLLIN;
|
||||
|
||||
fds[ 1 ].fd = n->fd();
|
||||
fds[ 1 ].events = POLLIN;
|
||||
Select sel;
|
||||
sel.add_fd( STDIN_FILENO );
|
||||
sel.add_fd( n->fd() );
|
||||
|
||||
while( true ) {
|
||||
try {
|
||||
if ( poll( fds, 2, n->wait_time() ) < 0 ) {
|
||||
perror( "poll" );
|
||||
if ( sel.select( n->wait_time() ) < 0 ) {
|
||||
perror( "select" );
|
||||
}
|
||||
|
||||
n->tick();
|
||||
|
||||
if ( fds[ 0 ].revents & POLLIN ) {
|
||||
if ( sel.read( STDIN_FILENO ) ) {
|
||||
char x;
|
||||
fatal_assert( read( STDIN_FILENO, &x, 1 ) == 1 );
|
||||
n->get_current_state().push_back( Parser::UserByte( x ) );
|
||||
}
|
||||
|
||||
if ( fds[ 1 ].revents & POLLIN ) {
|
||||
if ( sel.read( n->fd() ) ) {
|
||||
n->recv();
|
||||
}
|
||||
} catch ( NetworkException e ) {
|
||||
|
||||
Reference in New Issue
Block a user