问题描述
我正在Ocaml中使用TCP/IP套接字开发协议,并且我有兴趣实现事件驱动方法.基本上,我想使事件处理函数在套接字接收到新数据或关闭或打开时调用.
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.
是否可以在Ocaml中进行操作而无需使用多线程手动实现?
Is it possible to do in Ocaml without implementing it manually using multiple threads?
谢谢
推荐答案
是.循环播放并使用 Unix.select
来等待事件发生fds.您必须使用 Unix.set_nonblock
将套接字设置为非阻塞模式a>,这样您的读取和写入操作就不会被阻塞,并且如果没有可读取/写入的数据,您可以回到选择状态(因为即使select
返回的fds都是可读/可写的,也并不意味着a对它们的读/写不会被阻止).
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).
这篇关于Ocaml中的套接字onread,onready,onclose事件处理函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!