github.com/volts-dev/volts@v0.0.0-20240120094013-5e9c65924106/transport/tcp_sock.go (about) 1 package transport 2 3 import ( 4 "errors" 5 "net" 6 "time" 7 ) 8 9 type tcpTransportSocket struct { 10 conn net.Conn 11 // transport ITransport // NOTE 添加到自ROUTER耦合度极度降低 12 13 // ReadTimeout sets readdeadline for underlying net.Conns 14 ReadTimeout time.Duration 15 // WriteTimeout sets writedeadline for underlying net.Conns 16 WriteTimeout time.Duration 17 18 //enc *gob.Encoder 19 //dec *gob.Decoder 20 //encBuf *bufio.Writer 21 } 22 23 func NewTcpTransportSocket(conn net.Conn, readTimeout, writeTimeout time.Duration) *tcpTransportSocket { 24 //encBuf := bufio.NewWriter(conn) 25 return &tcpTransportSocket{ 26 conn: conn, 27 ReadTimeout: readTimeout, 28 WriteTimeout: writeTimeout, 29 //encBuf: encBuf, 30 //enc: gob.NewEncoder(encBuf), // FIXME 31 //dec: gob.NewDecoder(conn), // FIXME 32 } 33 } 34 func (t *tcpTransportSocket) Conn() net.Conn { 35 return t.conn 36 } 37 38 func (t *tcpTransportSocket) Local() string { 39 return t.conn.LocalAddr().String() 40 } 41 42 func (t *tcpTransportSocket) Remote() string { 43 return t.conn.RemoteAddr().String() 44 } 45 46 func (t *tcpTransportSocket) Recv(m *Message) error { 47 if m == nil { 48 return errors.New("message passed in is nil") 49 } 50 51 // set timeout if its greater than 0 52 if t.ReadTimeout > time.Duration(0) { 53 t.conn.SetDeadline(time.Now().Add(t.ReadTimeout)) 54 } 55 56 return m.Decode(t.conn) //return t.dec.Decode(&m) 57 } 58 59 func (t *tcpTransportSocket) Send(m *Message) error { 60 // set timeout if its greater than 0 61 if t.WriteTimeout > time.Duration(0) { 62 t.conn.SetDeadline(time.Now().Add(t.WriteTimeout)) 63 } 64 65 if _, err := t.conn.Write(m.Encode()); err != nil { 66 return err 67 } 68 69 return nil 70 } 71 72 func (t *tcpTransportSocket) Close() error { 73 return t.conn.Close() 74 }