Redirecting Buffers

Top  Previous  Next

The following example appeared under Receiving Data in TCP Mode:

 

 

sub on_sock_data_arrival

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

 sock.send

end sub

 

 

This example shows how to send all data incoming to the RX buffer out from the TX buffer, in just two lines of code. However fast, this technique still passes all data through your BASIC code, even though you are not processing (altering, sampling) it in any way.

A much more efficient and advanced way to do this would be using a technique called buffer redirection (buffer shorting). With buffer shorting, instead of receiving the data into the RX buffer of your socket, you are receiving it directly into the TX buffer of another object which is supposed to send out this data. This can be a socket (same or different one), a serial port object, etc.

To use buffer shorting, you invoke the sock.redir method and specify the buffer to which the data is to be redirected. Once this is done, the on_sock_data_arrival event won't be generated at all, because the data will be going directly to the TX buffer that you have specified. As soon as the data enters this buffer, it will be automatically committed for sending. Here is an example:

 

 

sub on_sys_init

 sock.num=0

 sock.redir(PL_REDIR_SOCK0) ' This is a loopback for socket 0.

end sub

 

 

The performance advantage here is enormous, due to two factors: first, you are not handling the data programmatically, so the VM isn't involved at all. And second, the data being received is received directly into the TX buffer from which it is transmitted, so there is less copying in memory.

Of course you cannot do anything at all with this data — you are just pumping it through. However, very often this is precisely what is needed! Additionally, you can still process inband commands/replies (messages).

To stop redirection, you can use sock.redir(0), which means "receive data into the RX buffer of the socket in a normal fashion".

Redirection and UDP

Using Buffers in UDP Mode explained that the sock object preserves buffer boundaries when storing UDP datagrams in RX and TX buffer. To achieve this, the sock object uses special datagram headers that are also stored in these buffers. This means that the buffers contain not only data, but also an additional "service" information.

When an RX buffer of a "UDP socket" (i.e. a socket running in the UDP mode) is redirected to a TX buffer of another UDP socket, datagram boundaries are preserved. The receiving socket will still send out the data subdivided into the original datagrams.

When an RX buffer of a UDP socket is redirected to a TX buffer of a TCP socket or serial port, the service information is removed and datagram boundaries are dissolved. To the receiving TCP socket or serial port, the data appears to be a stream.