github.com/godevsig/adaptiveservice@v0.9.23/stream.go (about) 1 package adaptiveservice 2 3 import ( 4 "net" 5 "time" 6 ) 7 8 // Netconn is the underlying net connection. 9 type Netconn interface { 10 // Close closes the connection. 11 // Any blocked Read or Write operations will be unblocked and return errors. 12 Close() error 13 // LocalAddr returns the local network address. 14 LocalAddr() net.Addr 15 // RemoteAddr returns the remote network address. 16 RemoteAddr() net.Addr 17 } 18 19 // Connection is the connection between client and server. 20 type Connection interface { 21 // default stream. 22 Stream 23 // NewStream creates a new stream. 24 NewStream() Stream 25 // Close closes the connection. 26 Close() 27 } 28 29 // Stream is an independent channel multiplexed from the underlying connection. 30 type Stream interface { 31 // Send sends a message to the stream peer. If msg is an error value, it will 32 // be received and returned by peer's Recv() as error. 33 Send(msg interface{}) error 34 35 // Recv receives a message from the stream peer and stores it into the value 36 // that msgPtr points to. 37 // 38 // msgPtr can be nil, where user only cares about error, otherwise 39 // it panics if msgPtr is not a non-nil pointer. 40 Recv(msgPtr interface{}) error 41 42 // SendRecv combines send and receive on the same stream. 43 SendRecv(msgSnd interface{}, msgRcvPtr interface{}) error 44 45 // RecvTimeout is Recv with timeout, returns ErrRecvTimeout if timout happens. 46 //RecvTimeout(msgPtr interface{}, timeout time.Duration) error 47 48 // GetNetconn gets the transport connection. 49 GetNetconn() Netconn 50 51 // SetRecvTimeout sets the timeout for each Recv(), which waits at least duration 52 // d and returns ErrRecvTimeout if no data was received within that duration. 53 // A negative or zero duration causes Recv() waits forever. 54 // Default is 0. 55 SetRecvTimeout(d time.Duration) 56 } 57 58 // ContextStream is a stream with an associated context. 59 // Messages from the same stream have the same context, their handlers 60 // may be executed concurrently. 61 type ContextStream interface { 62 Context 63 Stream 64 } 65 66 type timeouter struct { 67 d time.Duration 68 } 69 70 func (to *timeouter) SetRecvTimeout(d time.Duration) { 71 to.d = d 72 } 73 74 func (to *timeouter) timeoutChan() (timeoutChan chan struct{}) { 75 if to.d > 0 { 76 timeoutChan = make(chan struct{}, 1) 77 time.AfterFunc(to.d, func() { timeoutChan <- struct{}{} }) 78 } 79 return 80 }