2 * Test name: test07_srv.c
4 * Objective: Test an impatient TCP server with a timeout.
6 * Description: Implements an echo server using the TCP protocol. It is
7 * based on test06_srv.c but has a timeout for receiving data from a client
8 * and if the time is up it sends an angry message to the client requesting
9 * for more information.
12 #include <sys/types.h>
13 #include <sys/ioctl.h>
14 #include <sys/select.h>
16 #include <sys/asynchio.h>
24 #include <net/netlib.h>
25 #include <net/gen/netdb.h>
26 #include <net/gen/in.h>
27 #include <net/gen/tcp.h>
28 #include <net/gen/tcp_io.h>
30 #include <net/gen/inet.h>
34 int my_listen(long port
) {
38 nwio_tcpconf_t tcpconf
;
39 nwio_tcpcl_t tcplistenopt
;
41 /* Get default UDP device */
42 if ((tcp_device
= getenv("TCP_DEVICE")) == NULL
)
43 tcp_device
= TCP_DEVICE
;
45 /* Open TCP connection */
46 if ((netfd
= open(tcp_device
, O_RDWR
)) < 0)
48 fprintf(stderr
,"Error opening TCP connection\n");
52 /* Configure TCP connection */
53 tcpconf
.nwtc_flags
= NWTC_LP_SET
| NWTC_UNSET_RA
| NWTC_UNSET_RP
;
54 tcpconf
.nwtc_locport
= (tcpport_t
) htons(port
);
56 if ((ioctl(netfd
, NWIOSTCPCONF
, &tcpconf
))<0)
58 fprintf(stderr
,"Error configuring the connection\n");
63 /* Get communication options */
64 if ((ioctl(netfd
, NWIOGTCPCONF
, &tcpconf
)) < 0) {
65 fprintf(stderr
, "Error getting configuration\n");
70 /* Set conf options */
71 tcplistenopt
.nwtcl_flags
= 0;
72 printf("Waiting for connections...\n");
73 while ((ioctl(netfd
, NWIOTCPLISTEN
, &tcplistenopt
)) == -1)
77 fprintf(stderr
,"Unable to listen for connections\n");
85 int main(int argc
,char *argv
[]) {
91 struct timeval timeout
;
93 if ((fd
= my_listen(PORT
)) < 0) {
96 printf("Waiting for messages on port: %ld\n", PORT
);
101 /* Initialize fd_set */
103 FD_SET(fd
, &fds_read
);
107 /* Wait for data available to be read (no timeout) */
108 ret
= select(4, &fds_read
, NULL
, NULL
, &timeout
);
110 fprintf(stderr
, "Error on select: %d\n", errno
);
115 strcpy(buffer
, "I want to get some data!!\n");
116 write(fd
, &buffer
, 1024);
120 /* data received from client */
121 if (FD_ISSET(fd
, &fds_read
)) {
122 printf("Ready to receive...\n");
123 /* Read received data */
124 data_read
= read(fd
, &buffer
, 1024);
125 printf("Received data: %s\n", buffer
);
127 /* Can exit if the received string == exit */
128 if (!strcmp(buffer
,"exit"))
131 /* Write the same back */
132 write(fd
, &buffer
, data_read
);
135 printf("Connection finished\n");