Created
February 2, 2011 21:52
-
-
Save morgan-murray/808529 to your computer and use it in GitHub Desktop.
Example of a socket read/write pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Start | |
listen_fd = socket()...bind()... | |
client_fd = -1; | |
// Main loop | |
FD_SET(listen_fd,readfds); | |
if(client_fd != -1) | |
FD_SET(client_fd,readfds); | |
N = listen_fd + 1; | |
if(client_fd > listen_fd) | |
N = client_fd + 1; /* stupid semantics require N to be one more than the highest fd to wait for */ | |
struct timeval tv = { 0,0}; /* timeout: 0 seconds, 0 microseconds */ | |
i = select(N,&readfds,NULL,NULL,tv); | |
if(FD_ISSET(readfds,listen_fd)){ | |
i = accept(listen_fd); | |
if(client_Fd == -1) | |
close(i); /* we already have a client, close connection immediately */ | |
else | |
client_fd = i; | |
} | |
if(client-Fd != -1 && FD_ISSET(client_fd,readfds)){ | |
char c; | |
i = read(client_fd,&c,1)); /* read a single byte */ | |
if(c == START_BYTE)... | |
if(c == STOP_BYTE)... | |
} | |
// Final block | |
if(i== 0 /* 0 byte read == EOF */){ | |
close(client_fd); | |
client_Fd = -1; | |
} | |
if(i == -1){ /* error?! */ | |
perror("client_Read"); | |
close(client_fd); | |
client_fd = -1; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an example of a read/write pattern for sockets shared by Chris via IM.