newlisp读取数据超时功能

newlisp没有提供读取socket数据超时返回的功能。

自己实现了一个:

;; socket.lsp

(context 'socket)

;; return the number of bytes which are ready to read
;; throw error if connection is closed
(define (net-peek-ex s)
  (unless (net-peek s)
	  (throw-error "connection is closed")))

;; read specified size of data from connection in specified milliseconds
;; s means socket
;; timeout means waiting for milliseconds
;; return the receivied data
;; return () if timeout
(define (read-data s timeout number)
  (let ((t (time-of-day)) (r 0))
    (catch
     (while true
	    (begin 
	      (sleep 1)
	      (set 'r (net-peek-ex s))
	      (if (> r 0) (throw r))
	      (if (> (- (time-of-day) t) timeout) (throw -1))
	      )) 'q)
    (if (!= -1 q)
	(begin (net-receive s buffer (min q number)) buffer)
	'()
	)))


(define (test)
  ;;(set 's (net-connect "localhost" 7777))
  (set 's (net-connect "www.baidu.com" 80))
  (let (x (read-data s 50 10 buff))
    (if x (println x) (println "nil:" x))
  ))





你可能感兴趣的:(newlisp读取数据超时功能)