Differences

This shows you the differences between two versions of the page.

Link to this comparison view

sdk:scripts:tcpserver [2015/05/05 15:04]
sdk:scripts:tcpserver [2015/05/05 15:04] (current)
Line 1: Line 1:
 +====== SDK Script tcpserver.are ======
 +<code c tcpserver.are>​
 +/* DESC: This script implements a TCP server which is able to receive messages.
 + * Copyright (C) 2012 NetModule AG, Switzerland
 + */
 +
 +MAX_CONNECTIONS = 1;
 +
 +void usage()
 +{
 +    printf("​usage:​ tcpserver.are <​port>​\n"​);​
 +    exit(1);
 +}
 +
 +if (argc < 2) {
 +    usage();
 +}
 +
 +port = (int) argv[1];
 +timeout = 10;
 +
 +sock = socket(AF_INET,​ SOCK_STREAM,​ IPPROTO_TCP);​
 +if (sock < 0) {
 +    printf("​Unable to open socket\n"​);​
 +    exit(1);
 +}
 +
 +ret = bind(sock, port, ""​);​
 +if (ret == -1) {
 +    printf("​Unable to bind port %d\n", port);
 +    close(sock);​
 +    exit(1);
 +}
 +
 +ret = listen(sock,​ MAX_CONNECTIONS);​
 +if (ret == -1) {
 +    printf("​Unable to listen\n"​);​
 +    close(sock);​
 +    exit(1);
 +}
 +
 +printf("​Listening for connections on port %d\n", port);
 +
 +quit = 0;
 +while (!quit) {
 +    client = accept(sock);​
 +    if (client < 0) {
 +        printf("​accept failed\n"​);​
 +        sleep(1);
 +        continue;
 +    }   
 +
 +    printf("​New client connected\n"​);​
 +    ​
 +    while (1) {
 +        /* wait for socket data  */
 +        rv = select(client,​ timeout);
 +
 +        if (rv == -1) {
 +            printf("​Error during select()\n"​);​
 +            close(sock);​
 +            exit(1);
 +        } else if (rv == 0) {
 +            //​printf("​timeout\n"​);​
 +        } else {
 +            // one or both of the descriptors have data
 +            msg = recv(client);​
 +            if (left(msg,​4) == "​quit"​) {
 +                printf("​received quit, terminating\n"​);​
 +                quit = 1;
 +                break;
 +               }
 +            if (left(msg,​3) == "​bye"​){
 +                printf("​received bye, closing connection...\n"​);​
 +                break;
 +            } else if (msg != ""​) {        ​
 +                printf("​rcvd:​ '​%s'​\n",​ msg);
 +            }
 +        }
 +    }
 +    close(client);​
 +}
 +
 +close(sock);​
 +
 +exit(0);
 +
 +</​code>​