connection.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package ray
  2. import (
  3. "io"
  4. "net"
  5. "time"
  6. "v2ray.com/core/common/buf"
  7. )
  8. type connection struct {
  9. stream Ray
  10. closed bool
  11. localAddr net.Addr
  12. remoteAddr net.Addr
  13. reader *buf.BufferedReader
  14. writer buf.Writer
  15. }
  16. // NewConnection wraps a Ray into net.Conn.
  17. func NewConnection(stream InboundRay, localAddr net.Addr, remoteAddr net.Addr) net.Conn {
  18. return &connection{
  19. stream: stream,
  20. localAddr: localAddr,
  21. remoteAddr: remoteAddr,
  22. reader: buf.NewBufferedReader(stream.InboundOutput()),
  23. writer: stream.InboundInput(),
  24. }
  25. }
  26. // Read implements net.Conn.Read().
  27. func (c *connection) Read(b []byte) (int, error) {
  28. if c.closed {
  29. return 0, io.EOF
  30. }
  31. return c.reader.Read(b)
  32. }
  33. // ReadMultiBuffer implements buf.Reader.
  34. func (c *connection) ReadMultiBuffer() (buf.MultiBuffer, error) {
  35. return c.reader.ReadMultiBuffer()
  36. }
  37. // Write implements net.Conn.Write().
  38. func (c *connection) Write(b []byte) (int, error) {
  39. if c.closed {
  40. return 0, io.ErrClosedPipe
  41. }
  42. l := len(b)
  43. mb := buf.NewMultiBufferCap(l/buf.Size + 1)
  44. mb.Write(b)
  45. return l, c.writer.WriteMultiBuffer(mb)
  46. }
  47. func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
  48. if c.closed {
  49. return io.ErrClosedPipe
  50. }
  51. return c.writer.WriteMultiBuffer(mb)
  52. }
  53. // Close implements net.Conn.Close().
  54. func (c *connection) Close() error {
  55. c.closed = true
  56. c.stream.InboundInput().Close()
  57. c.stream.InboundOutput().CloseError()
  58. return nil
  59. }
  60. // LocalAddr implements net.Conn.LocalAddr().
  61. func (c *connection) LocalAddr() net.Addr {
  62. return c.localAddr
  63. }
  64. // RemoteAddr implements net.Conn.RemoteAddr().
  65. func (c *connection) RemoteAddr() net.Addr {
  66. return c.remoteAddr
  67. }
  68. // SetDeadline implements net.Conn.SetDeadline().
  69. func (c *connection) SetDeadline(t time.Time) error {
  70. return nil
  71. }
  72. // SetReadDeadline implements net.Conn.SetReadDeadline().
  73. func (c *connection) SetReadDeadline(t time.Time) error {
  74. return nil
  75. }
  76. // SetWriteDeadline implement net.Conn.SetWriteDeadline().
  77. func (c *connection) SetWriteDeadline(t time.Time) error {
  78. return nil
  79. }