SELECT.SOCKET() |
|
|
The SELECT.SOCKET() function monitors multiple sockets for events.
Format
SELECT.SOCKET(skt.array, timeout)
where
The SELECT.SOCKET() enables a developer to write a program that can serve multiple socket connections, pausing execution until an event occurs on any socket.
Use the SKT$INFO.EVENTS key to the SET.SOCKET.MODE() function to set the events to be monitored (read, write, exception) on each socket in the array. Then use SELECT.SOCKET() to wait for an event to occur.
If an event is detected, the function returns a dynamic array with a field to correspond to each element in skt.array. The content of each field is a combination of uppercase letters R for a read event, W for a write event and E for an exception event. Only events that have been selected for monitoring will appear. Fields for which no event has occurred or where the corresponding element of skt.array is not a socket variable will be blank. Alternatively, the SOCKET.INFO() function can be used with key value SKT$INFO.EVENTS against each element of skt.array to check for the socket status.
If the function returns as a result of a timeout or an error, the returned value is a null string and the STATUS() function can be used to determine the cause. A timeout will return ER$TIMEOUT. All other values are errors.
The events that can be monitored are
The example below shows the general principles of using socket event notification, monitoring multiple incoming connections on port 9000. A real program would need to include additional error handling.
$include keys.h
dim skt(10)
skt(1) = create.server.socket('', 9000, 0) if status() then stop 'Cannot initialise server socket'
if not(set.socket.mode(skt(1), SKT$INFO.EVENTS, SKT$READ.EVENT)) then stop 'Error from set.socket.mode()' end
loop events = select.socket(skt, 5000) for i = 1 to 10 if events<i> then ;* Must be a read event if i = 1 then ;* New connection * Find an unused table entry for j = 2 to 10 if not(socket.info(skt(j), SKT$INFO.OPEN)) then skt(j) = accept.socket.connection(skt(1), 0) if not(set.socket.mode(skt(j), SKT$INFO.EVENTS, SKT$READ.EVENT)) then stop 'Error from set.socket.mode()' end exit end next j end else str = read.socket(skt(i), 1000, 0, 0) if status() then ;* Socket closed skt(i) = 0 end else ...process input... end end end next i repeat
See also: Using Socket Connections, ACCEPT.SOCKET.CONNECTION, CLOSE.SOCKET, CREATE.SERVER.SOCKET(), OPEN.SOCKET(), READ.SOCKET(), SERVER.ADDR(), SET.SOCKET.MODE(), WRITE.SOCKET() |