Event Socket.Write (gb.net)

Event Write ( )

This event is raised when the internal socket send buffers can take in more data.

This event is most useful if you want to send a large file. The Write event is not raised continuously (as a socket is almost always ready to take in data). You have to signal to Gambas that you have some data to write by doing an initial Write to the socket. After the initial write, the Write event will be raised continuously for as long as you write more data from the Write event handler.

Example

The following is an example of serving a large static file via HTTP. Since the socket's send buffers in kernel space are only a few kilobytes big, the data should be written in chunks to avoid blocking for too long. The kernel takes care of sending the data and notifies you with a Write event when more space is available. The overall memory consumption remains tiny, the whole file is never loaded into memory entirely. The HTTP header serves as the initial write.

Private $hServer As ServerSocket

Public Sub Main()
  $hServer = New ServerSocket As "Server"
  $hServer.Type = Net.Internet
  $hServer.Port = 8080
  $hServer.Listen
End

Public Sub Server_Connection(RemoteHostIP As String)
  $hServer.Accept()
End

Public Sub Socket_Read()
  Dim sBuf As String
  Dim sResponse As String

  ' Assemble and parse the HTTP request here...
  sBuf = Read #Last, -4096

  ' Just always send that one large file
  sResponse = Subst$("HTTP/1.1 200 OK\r\nContent-Length: &1\r\n\r\n", Stat("large_file.txt").Size)
  Write #Last, sResponse, Len(sResponse)
  ' The above Write kicks off a cycle of Write events which consume the stream
  ' registered in the socket's Tag property.
  Last.Tag = Open "large_file.txt" For Read
End

Public Sub Socket_Write()
  Dim hFile As Stream = Last.Tag
  Dim sBuf As String

  If Not Eof(hFile) Then
    ' Read a chunk of at most 4KiB from the file and send it to the socket.
    sBuf = Read #hFile, -4096
    Write #Last, sBuf
  Endif
  ' Once we didn't write anything, the cycle of Write events will stop.
End