forked from wmnsk/go-m3ua
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
59 lines (50 loc) · 1.31 KB
/
client.go
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
// Copyright 2018-2020 go-m3ua authors. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
package m3ua
import (
"context"
"fmt"
"sync"
"time"
"github.com/ishidawataru/sctp"
)
// Dial establishes a M3UA connection as a client.
//
// After successfully established the connection with peer, state-changing
// signals and heartbeats are automatically handled background in another goroutine.
func Dial(ctx context.Context, net string, laddr, raddr *sctp.SCTPAddr, cfg *Config) (*Conn, error) {
var err error
conn := &Conn{
mu: new(sync.Mutex),
mode: modeClient,
stateChan: make(chan State),
established: make(chan struct{}),
sctpInfo: &sctp.SndRcvInfo{PPID: 0x03000000, Stream: 0},
cfg: cfg,
}
if conn.cfg.HeartbeatInfo.Interval == 0 {
conn.cfg.HeartbeatInfo.Enabled = false
}
n, ok := netMap[net]
if !ok {
return nil, fmt.Errorf("invalid network: %s", net)
}
conn.sctpConn, err = sctp.DialSCTP(n, laddr, raddr)
if err != nil {
return nil, err
}
go func() {
conn.stateChan <- StateAspDown
}()
go conn.monitor(ctx)
select {
case _, ok := <-conn.established:
if !ok {
return nil, ErrFailedToEstablish
}
return conn, nil
case <-time.After(10 * time.Second):
return nil, ErrTimeout
}
}