'
' A multithreaded TCP/IP server allowing multiple client connections.
'
' From different shells use 'telnet localhost 51000' to connect. These are all served.
'
' September 2010, PvE - GPL
'---------------------------------------------------------------------------------------------------

INCLUDE "pthread.bac"

CONST NUM_THREADS = 256

DECLARE threads[NUM_THREADS]
DECLARE mutex TYPE pthread_mutex_t
DECLARE count

' Initialize mutex
pthread_mutex_init(ADDRESS(mutex), 0)

'---------------------------------------------------------------------------------------------------

SUB Handle_Connection(int net)

    LOCAL dat$, query$

    REPEAT

        pthread_mutex_lock(ADDRESS(mutex))

        IF WAIT(net, 50) THEN
            RECEIVE dat$ FROM net
            PRINT "Found: ", dat$;

            SEND CONCAT$("Total connections: ", STR$(count), NL$) TO net

            ' Cut off newline
            query$ = CHOP$(dat$)
        ENDIF

        pthread_mutex_unlock(ADDRESS(mutex))

        SLEEP 50

    ' Thread safe comparison
    UNTIL EQUAL(query$, "quit")

    CLOSE SERVER net
    DECR count

    pthread_exit(0)

END SUB

'---------------------------------------------------------------------------------------------------

PRINT "============================"
PRINT "*** Multithreaded SERVER ***"
PRINT "============================"
PRINT

PRINT "Connect from other terminals with 'telnet localhost 51000' and enter text - 'quit' ends."

REPEAT

    OPEN "localhost:51000" FOR SERVER AS mynet

    rc = pthread_create(ADDRESS(threads[count]), 0, Handle_Connection, mynet)

    IF rc THEN
        PRINT "ERROR: could not create thread, errorcode: ", rc
        END 1
    ELSE
        INCR count
    END IF

UNTIL count IS NUM_THREADS

CLOSE SERVER mynet

pthread_mutex_destroy(ADDRESS(mutex))
pthread_exit(0)

PRINT "Server mode finished!"