zhangmeng
2020-08-04 4acab9cb4dae6ddc881e6bd5454715063c1a7d4b
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package softbus
 
/*
#include <stdlib.h>
#include "libcsoftbus.h"
*/
import "C"
import (
    "errors"
    "fmt"
    "unsafe"
)
 
const (
 
    // RETVAL retual val
    RETVAL = 0x7fff
    // PullPush mode
    PullPush = 1
    // ReqRep mode
    ReqRep = 2
    // Pair mode
    Pair = 3
    // PubSub mode
    PubSub = 4
    // Survey mode
    Survey = 5
    // Bus mode
    Bus = 6
)
 
// Socket struct
type Socket struct {
    csocket unsafe.Pointer
}
 
// OpenSocket open
func OpenSocket(mod int) *Socket {
    if libsoftbus == nil {
        return nil
    }
 
    s := C.wrap_fn_socket_open(libsoftbus, C.int(mod))
    if s == nil {
        return nil
    }
 
    return &Socket{
        csocket: s,
    }
}
 
// Close socket
func (s *Socket) Close() int {
    if libsoftbus != nil || s.csocket != nil {
        r := C.wrap_fn_socket_close(libsoftbus, s.csocket)
        return int(r)
    }
    return RETVAL
}
 
// Bind socket
func (s *Socket) Bind(port int) int {
    if libsoftbus == nil {
        return RETVAL
    }
 
    r := C.wrap_fn_socket_bind(libsoftbus, s.csocket, C.int(port))
    return int(r)
}
 
// Listen socket
func (s *Socket) Listen() int {
    if libsoftbus == nil {
        return RETVAL
    }
    r := C.wrap_fn_socket_listen(libsoftbus, s.csocket)
    return int(r)
}
 
// Connect socket
func (s *Socket) Connect(port int) int {
    if libsoftbus == nil {
        return RETVAL
    }
 
    r := C.wrap_fn_socket_connect(libsoftbus, s.csocket, C.int(port))
    return int(r)
}
 
// Send data
func (s *Socket) Send(data []byte) int {
    if libsoftbus == nil {
        return RETVAL
    }
 
    r := C.wrap_fn_socket_send(libsoftbus, s.csocket, unsafe.Pointer(&data[0]), C.int(len(data)))
    return int(r)
}
 
// Recv data
func (s *Socket) Recv() ([]byte, error) {
    if libsoftbus == nil {
        return nil, errors.New("libsoftbus is nil")
    }
 
    var rd unsafe.Pointer
    var rl C.int
    r := C.wrap_fn_socket_recv(libsoftbus, s.csocket, &rd, &rl)
    if r != 0 {
        return nil, fmt.Errorf("Recv Data Failed errCode: %d", int(r))
    }
    data := C.GoBytes(rd, rl)
    C.wrap_fn_socket_buf_free(libsoftbus, rd)
    return data, nil
}
 
// Port get port/key
func (s *Socket) Port() int {
    if libsoftbus == nil {
        return -1
    }
 
    r := C.wrap_fn_socket_port(libsoftbus, s.csocket)
 
    return int(r)
}