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)
|
}
|