8. int main(int argc, char *argv[])
{
int sock; /* Socket descriptor */
if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
/* it would resolve the host name here */
if (connect(sock to server))
DieWithError("connect() failed");
do {
select(maxfd+1, sock, …); /* wait for socket to become readable
or writable */
if(check sock if writable)
send(sock, string, string_len, 0);
if(check sock if readable)
recv(sock, string, string_len, 0);
} while(everything is fine);
close(sock);
exit(0);
}
School book example
1
2
1
3
4
5
10. int main(int argc, char *argv[])
{
int sock[NUM_CONNS]; /* Socket descriptors */
for(i=0; i< NUM_CONNS; i++) {
if ((sock[i] = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
if (connect(sock[i] to server[i]))
DieWithError("connect() failed");
do {
/* set up the bitmasks for select() */
select(maxfd+1, sock, …); /* wait for any socket to become readable
or writable */
for(i=0; i< NUM_CONNS; i++) {
if(check sock[i] if writable)
send(sock, string, string_len, 0);
if(check sock[i] if readable)
recv(sock, string, string_len);
}
} while(everything is fine);
close(sock);
exit(0);
}
More connections
1
2
1
3
4
5
11. int main(int argc, char *argv[])
{
int sock[NUM_CONNS]; /* Socket descriptors */
for(i=0; i< NUM_CONNS; i++) {
if ((sock[i] = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithError("socket() failed");
if (connect(sock[i] to server[i]))
DieWithError("connect() failed");
do {
/* set up the bitmasks for select() */
select(maxfd+1, sock, …); /* wait for any socket to become readable
or writable */
for(i=0; i< NUM_CONNS; i++) {
if(check sock[i] if writable)
send(sock, string, string_len, 0);
if(check sock[i] if readable)
recv(sock, string, string_len);
}
} while(everything is fine);
close(sock);
exit(0);
}
More connections
26. simple event client
int function(int socketfd)
{
ev = ev_default_loop();
ev_timer_init(..., timer_callback, …);
ev_io_init(ev, event_callback, socketfd, WHAT);
ev_loop(ev); /* sit here until done */
}
int timer_callback(...)
{
/* timer expired! */
}
int event_callback(..., int socketfd, ...)
{
/* something happened on my socket, now we
recv or send etc */
}