OCaml is a great language with its type system and module system. But I have to say that it’s nightmare to find some docs or examples some very base usage.
For example, I want to write a simple udp server, after google it, I got an example from SO
open Core
open Async
let wait_for_datagram () =
let port = 9999 in
let addr = Socket.Address.Inet.create Unix.Inet_addr.localhost ~port in
let%bind socket = Udp.bind addr in
let socket = Socket.fd socket in
let stop = never () in
let config = Udp.Config.create ~stop () in
let callback buf _ : unit = failwith "got a datagram" in
Udp.recvfrom_loop ~config socket callback
But it’s error on let%bind socket = Udp.bind addr in
as follows:
Error: This expression has type
([ `Bound ], Async_extra__.Import.Socket.Address.Inet.t)
Async_extra__.Import.Socket.t =
([ `Bound ], Async_extra__.Import.Socket.Address.Inet.t)
Async_unix__Unix_syscalls.Socket.t
but an expression was expected of type
'a Async_kernel__Deferred.t = 'a Async_kernel__Types.Deferred.t
So I have to read the source code of async_extra:
val bind
: ?ifname : string
-> Socket.Address.Inet.t
-> ([ `Bound ], Socket.Address.Inet.t) Socket.t
Yes, bind
would return a [Bound],...
, but why the guys from SO works?
It just cost me a few minutes to find a Python UDP server example:
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 10000)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
while True:
print >>sys.stderr, '\nwaiting to receive message'
data, address = sock.recvfrom(4096)
print >>sys.stderr, 'received %s bytes from %s' % (len(data), address)
print >>sys.stderr, data
if data:
sent = sock.sendto(data, address)
print >>sys.stderr, 'sent %s bytes back to %s' % (sent, address)
It would be better to add some more basic example on GitHub or some wiki else.