This repository has been archived on 2022-09-10. You can view files and clone it, but cannot push or open issues or pull requests.
tunnel/connection.go

63 lines
875 B
Go
Raw Normal View History

2022-09-09 06:05:20 +00:00
package tunnel
2022-09-09 11:38:41 +00:00
import (
"io"
"sync"
)
2022-09-09 06:05:20 +00:00
type Connection struct {
2022-09-09 06:31:47 +00:00
RX <-chan *DataFrame
TX chan<- *DataFrame
ID ID
closed bool
2022-09-09 13:16:36 +00:00
logger Logger
}
func (c *Connection) SetLogger(logger Logger) {
c.logger = logger
2022-09-09 06:05:20 +00:00
}
func (c *Connection) Read(p []byte) (int, error) {
df, ok := <-c.RX
if !ok {
return 0, c.Close()
}
return df.Read(p)
}
func (c *Connection) Write(p []byte) (int, error) {
2022-09-09 11:38:41 +00:00
var lock sync.Mutex
lock.Lock()
defer lock.Unlock()
if c.closed {
return 0, io.ErrClosedPipe
}
2022-09-09 06:05:20 +00:00
df := &DataFrame{
ID: c.ID,
Type: TypeNormal,
}
n, err := df.Write(p)
if err != nil {
return 0, err
}
c.TX <- df
return n, nil
}
func (c *Connection) Close() error {
2022-09-09 11:38:41 +00:00
var lock sync.Mutex
2022-09-09 06:05:20 +00:00
defer close(c.TX)
2022-09-09 06:31:47 +00:00
if !c.closed {
c.TX <- &DataFrame{
ID: c.ID,
Type: TypeClosed,
}
}
2022-09-09 11:38:41 +00:00
lock.Lock()
2022-09-09 06:31:47 +00:00
c.closed = true
2022-09-09 11:38:41 +00:00
lock.Unlock()
2022-09-09 06:05:20 +00:00
return nil
}