如何使用Socket.select

时间:2015-06-05 14:33:54

标签: sockets select sml

如何在标准ML中使用Socket.select

根据docs,我应该传递三个套接字列表和一个超时option,并且当任何套接字准备好做某事时函数返回(我假设,但不确定外部列表中的套接字需要注意的那些套接字)。但是,

  1. 输入似乎既不是元组,也不是四个参数。我如何构建适当的输入结构?
  2. select接收并返回sock_desc的列表,似乎没有办法从socket获得sock_desc。似乎也没有一种构建有效映射的方法,因为似乎不可能订购两个sock_desc,只是将它们进行相等性比较。从select获得返回值后,如何对返回的套接字执行任何有用的操作,例如写出响应,或者对它们调用accept

1 个答案:

答案 0 :(得分:2)

  1. 输入参数是一个包含四个字段的记录,因此您的代码应如下所示:
  2. Socket.select {
      rds = readSocketDescs,
      wrs = writeSocketDescs,
      exs = exnSocketDescs,
      timeout = SOME (Time.fromSeconds 10)
    }
    
    1. 是的,不确定,可能您需要使用列表自己保留映射。效率不高,但我看不出你还能做些什么。
    2. (**
       * 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