muxado.go 1.92 KB
Newer Older
Jeromy's avatar
Jeromy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package peerstream_muxado

import (
	"net"

	smux "QmPxuHs2NQjz16gnvndgkzHkm5PjtqbB5rwoSpLusBkQ7Q/go-stream-muxer"
	muxado "QmfEm573cZeq3LpgccZMpngV6dXbm5gfU23F5nNUuhSxxJ/muxado"
)

// stream implements smux.Stream using a ss.Stream
type stream struct {
	ms muxado.Stream
}

func (s *stream) muxadoStream() muxado.Stream {
	return s.ms
}

func (s *stream) Read(buf []byte) (int, error) {
	return s.ms.Read(buf)
}

func (s *stream) Write(buf []byte) (int, error) {
	return s.ms.Write(buf)
}

func (s *stream) Close() error {
	return s.ms.Close()
}

// Conn is a connection to a remote peer.
type conn struct {
	ms muxado.Session

	closed chan struct{}
}

func (c *conn) muxadoSession() muxado.Session {
	return c.ms
}

func (c *conn) Close() error {
	return c.ms.Close()
}

func (c *conn) IsClosed() bool {
	select {
	case <-c.closed:
		return true
	default:
		return false
	}
}

// OpenStream creates a new stream.
func (c *conn) OpenStream() (smux.Stream, error) {
	s, err := c.ms.Open()
	if err != nil {
		return nil, err
	}

	return &stream{ms: s}, nil
}

// AcceptStream accepts a stream opened by the other side.
func (c *conn) AcceptStream() (smux.Stream, error) {
	s, err := c.ms.Accept()
	if err != nil {
		return nil, err
	}
	return &stream{ms: s}, nil
}

// Serve starts listening for incoming requests and handles them
// using given StreamHandler
func (c *conn) Serve(handler smux.StreamHandler) {
	for { // accept loop
		s, err := c.AcceptStream()
		if err != nil {
			return // err always means closed.
		}
		go handler(s)
	}
}

type transport struct{}

// Transport is a go-peerstream transport that constructs
// spdystream-backed connections.
var Transport = transport{}

func (t transport) NewConn(nc net.Conn, isServer bool) (smux.Conn, error) {
	var s muxado.Session
	if isServer {
		s = muxado.Server(nc)
	} else {
		s = muxado.Client(nc)
	}
	cl := make(chan struct{})
	go func() {
		s.Wait()
		close(cl)
	}()
	return &conn{ms: s, closed: cl}, nil
}