A Code Snippet

Top  Previous  Next

Here is a small code snippet illustrating the process of getting and releasing sockets. We sacrificed robustness for simplicity, so don't take the code below for a shining example of sock. object's usage. Just see the parts related to the SOCK library — that's the point right now.

 

 

...

'set "#SOCK_MAX_SIGNATURE_LEN 4" and "#define SOCK_DEBUG_PRINT 1" before running this test

 

dim tcp_sock as byte 'to remember the socket number we've got

 

net.ip="192.168.1.93" '<--- edit as needed

 

'get a socket

tcp_sock=sock_get("TCPS")

'gotta check if there was a free socket for us...

if tcp_sock=255 then

 sys.halt '...uh-huh, out of sockets!

end if

 

'setup the socket

sock.num=tcp_sock

sock.rxbuffrq(1)

sock.txbuffrq(1)

sys.buffalloc

sock.protocol=PL_SOCK_PROTOCOL_TCP

sock.targetip="192.168.1.67" '<--- edit as needed

sock.targetport=10000 '<--- edit as needed

sock.connect

while sock.statesimple<>PL_SSTS_EST

wend

 

'send data -- we use the signature of the socket's user

sock.setdata(sock_who_uses(tcp_sock))

sock.send

while sock.txlen>0

wend

 

'close the connection

sock.close

while sock.statesimple<>PL_SSTS_CLOSED

wend

 

'release the socket

sock_release(tcp_sock)

...

 

 

And here is what appeared in the output pane of TIDE as the code executed:

 

 

SOCK> 'TCPS' got socket #2

SOCK> 'TCPS' released socket #2

 

 

The first message corresponds to sock_get(), the second one — to sock_release(). "TCPS" is the signature left by us, it stands for "TCP socket". The socket number obtained is 2 because we ran this code within a large program that uses a lot of other sockets for a lot of other things.

The example above establishes an outgoing connection to 192.168.1.67:10000. In our test, this was a PC running I/O Ninja, our sniffer/terminal software (you can get it at ninja.tibbo.com). We opened a "listener socket" on I/O Ninja, and here is what we saw:

 

 

Accepted TCP connection from 192.168.1.93:10254

TCPS

Remote node 192.168.1.93:10254 has closed TCP connection

 

 

This "TCPS" is the signature our code provided when calling sock_get(). The reason it appeared in Ninja is because of the sock.setdata(sock_who_uses(tcp_sock)) line in the code.