! Optional demo: requires a TCP server on 127.0.0.1:19002 on GaspardOS.
program socket_demo
  use gaspardos_gui
  implicit none
  type(GO64_SocketAddress), target :: address
  character(kind=c_char,len=6), target :: message = 'hello' // achar(10)
  integer(c_int64_t) :: fd, r, pause, sent
  integer :: attempt

  r = gof_ipv4(127, 0, 0, 1, 19002, c_loc(address))
  if (r < 0) stop 1
  fd = GO64_socket(GO64_AF_INET, GO64_STREAM, 0_c_int64_t)
  if (fd < 0) stop 2
  do attempt = 1, 1000
    r = GO64_connect(fd, c_loc(address), int(c_sizeof(address),c_int64_t))
    if (r /= -11) exit
    pause = GO64_yield()
  end do
  if (r >= 0) then
    sent = 0
    do attempt = 1, 1000
      r = GO64_send(fd, c_loc(message(sent+1:sent+1)), len(message,kind=c_int64_t)-sent, 0_c_int64_t)
      if (r > 0) sent = sent + r
      if (sent == len(message) .or. (r < 0 .and. r /= -11)) exit
      pause = GO64_yield()
    end do
    print *, 'bytes sent:', sent
  else
    print *, 'connect:', r
  end if
  do attempt = 1, 1000
    r = GO64_socket_close(fd)
    if (r /= -11) exit
    pause = GO64_yield()
  end do
  if (r < 0) stop 3
end program socket_demo
