如何在标准ML中使用Socket.select
?
根据docs,我应该传递三个套接字列表和一个超时option
,并且当任何套接字准备好做某事时函数返回(我假设,但不确定外部列表中的套接字仅需要注意的那些套接字)。但是,
select
接收并返回sock_desc
的列表,似乎没有办法从socket
获得sock_desc
。似乎也没有一种构建有效映射的方法,因为似乎不可能订购两个sock_desc
,只是将它们进行相等性比较。从select
获得返回值后,如何对返回的套接字执行任何有用的操作,例如写出响应,或者对它们调用accept
?答案 0 :(得分:2)
Socket.select {
rds = readSocketDescs,
wrs = writeSocketDescs,
exs = exnSocketDescs,
timeout = SOME (Time.fromSeconds 10)
}
(**
* Produces a list of all the pairs in `listPair`, whose keys are present
* in `whiteList`. Example:
*
* ```sml
* - filterListPair op= [(1,"a"), (2,"b"), (3,"c")] [2,3];
* val it = [(2,"b"),(3,"c")] : (int * string) list
* ```
*)
fun filterListPair eq listPair whiteList =
let
fun recur listPair whiteList result =
case (listPair, whiteList) of
([], _) => result
| (_, []) => result
| ((x, y) :: xs, k :: ks) =>
if eq (x, k)
then recur xs ks ((x, y) :: result)
else recur xs whiteList result
in
List.rev (recur listPair whiteList [])
end
val sockets = [ (* what have you *) ]
val descsToSockets = List.map (fn s => (Socket.sockDesc s, s)) sockets
val { rds, wrs, exs } = Socket.select {
rds = readSocketDescs,
wrs = writeSocketDescs,
exs = exnSocketDescs,
timeout = SOME (Time.fromSeconds 10)
}
(*
* The contract of Socket.select ensures that the order in input lists
* is preserved in the output lists, so we can use `filterListPair`.
*)
val selectedReadSockets =
filterListPair Socket.sameDesc descsToSockets rds