#include "vxworks.h"
#include "sockLib.h"
#include "inetLib.h"
#include "MyServer.h"

#define DEFAULT_SERVER_PORT 6699
int server;
SEM_ID Server_SM;
/*
* Start the function Server() as a task in AppInit() like this:
* int ret = 0;
* ret = taskSpawn("tServer", 165, 0x0002, 1024,(FUNCPTR) Server,
* 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
*/
void Server()
{
    int rc = 0, sd = 0;
    int addr_len = 0;
    int server_sock = 0;
    struct sockaddr_in server_addr, client_addr;

    memset(&server_addr, 0, sizeof(struct sockaddr_in));
    memset(&client_addr, 0, sizeof(struct sockaddr_in));
    server_sock = socket(AF_INET, SOCK_STREAM, 0);
    if (server_sock < 0) {
        printf("Failed to create Socket.\n");
        return;
    }
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(DEFAULT_SERVER_PORT);
    rc = bind(server_sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in));
    if (rc == -1) {
        close(server_sock);
        printf("Failed to bind socket\n");
        return;
    }
    rc = listen(server_sock, 2);
    if (rc == -1) {
        printf("socket listen error\n");
        return;
    }
    printf("TCP server is ready for receive connection request\n");
    while (1) {
        addr_len = sizeof(struct sockaddr_in);
        sd = accept(server_sock, (struct sockaddr *)&client_addr, &addr_len);
        if (sd <= 0) {
            printf("socket accept error\n");
            return;
        } else {
            printf("Socket connect success\n");
            server = sd;
            server_proc(sd);
        }
    }
}

void server_proc(int sock)
{
    int rc = 0;
    char buffer[32];
    fd_set socket;
    struct timeval wait;

    wait.tv_sec = 0;
    wait.tv_usec = 500000;

    while (server > 0) {
        FD_ZERO(&socket);
        FD_SET(sock, &socket);

        rc = select(FD_SETSIZE, &socket, (fd_set *) 0, (fd_set *) 0, &wait);
        if (rc == 0)
            continue;
        if (FD_ISSET(sock, &socket)) {
            semTake(Server_SM, WAIT_FOREVER);
            memset(buffer, 0, sizeof(buffer));
            rc = recv(sock, buffer, sizeof(buffer), 0);
            if (rc > 0) {
/* you can add your application specific code here */
                printf("RecvMsg:%s\n", buffer);
                semGive(Server_SM);
            } else {
                printf("Socket closed\n");
                close(sock);
                server = 0;
                semGive(Server_SM);
                break;
            }
        }
        taskDelay(10);
    }

}

/* end of the file */