Step 2: Adding TCP Comms

Top  Previous  Next

This and other projects in the Code Examples section are published on our website under the name "test_wln_lib".

 

Now let's take the previous example and create a TCP socket that will accept connections over the Wi-Fi interface. We will make a simple loopback socket that echoes back the data.

 

note_tip-wt

May we suggest our very own I/O NINJA terminal/sniffer software as the tool for testing the loopback socket? Hint: use Connection Socket plugin.

 

Only main.tbs needs to be changed from the previous example. The socket is configured in on_sys_init(). Notice how we don't just pick a random socket number to use. We obtain the socket from the SOCK library by calling sock_get(). This is very important! Once any part of your project uses the SOCK library (and WLN library does), all other parts of your project must do the same. Mess will ensue if you fail to handle socket numbers correctly.

In the code below, we first call wln_start() and then configure the loopback socket. There is no significance to this order and you can reverse it. Same goes for on_sock_data_arrival(). There is no special reason to call wln_proc_data() first, and handle the loopback socket next. You can reverse the order and everything will still work.

 

main.tbs:

 

include "global.tbh"

 

dim tcp_sock as byte

 

'====================================================================

sub on_sys_init()

 wln.ip="192.168.1.50" '<--- set suitable IP here

 

 if wln_start("TIBB1",WLN_SECURITY_MODE_WEP64,"12345678AB",PL_WLN_DOMAIN_FCC)<>WLN_STATUS_OK then

         sys.halt

 end if

 

 'configure loopback socket

 tcp_sock=sock_get("TCP")

 sock.num=tcp_sock

 sock.rxbuffrq(1)

 sock.txbuffrq(1)

 sys.buffalloc

 sock.protocol=PL_SOCK_PROTOCOL_TCP

 sock.localportlist="1000"

 sock.allowedinterfaces="WLN"

 sock.inconmode=PL_SOCK_INCONMODE_ANY_IP_ANY_PORT

 sock.reconmode=PL_SOCK_RECONMODE_3

end sub

 

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

sub on_sys_timer()

 wln_proc_timer()

end sub

 

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

sub on_sock_data_arrival()

 wln_proc_data()

 

 'loopback tcp data

 if sock.num=tcp_sock then

         sock.setdata(sock.getdata(sock.txfree))

         sock.send

 end if

end sub

 

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

sub on_wln_task_complete(completed_task as pl_wln_tasks)

 wln_proc_task_complete(completed_task)

end sub

 

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

sub on_wln_event(wln_event as pl_wln_events)

 wln_proc_event(wln_event)

end sub