问题
I am developing a protocol using TCP/IP socket in Ocaml and I am interested implementing the event driven approach. Basically, I want to make event handling functions that invokes whenever socket receives a new data or closed or opened.
Is it possible to do in Ocaml without implementing it manually using multiple threads?
Thanks,
回答1:
Yes. Make a loop and use Unix.select to wait for events on your fds. You will have to set your sockets to non-blocking mode with Unix.set_nonblock so that your reads and writes don't block and you can get back to your select if there's no data to read/write (because even if select
returns you fds that are readable/writable it doesn't mean that a read/write on them wouldn't block).
来源:https://stackoverflow.com/questions/16729842/socket-onread-onready-onclose-event-handler-function-in-ocaml