-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnetfd_bsd.go
61 lines (55 loc) · 1.7 KB
/
netfd_bsd.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
60
61
//
//
// Tencent is pleased to support the open source community by making tRPC available.
//
// Copyright (C) 2023 THL A29 Limited, a Tencent company.
// All rights reserved.
//
// If you have downloaded a copy of the tRPC source code from Tencent,
// please note that tRPC source code is licensed under the Apache 2.0 License,
// A copy of the Apache 2.0 License is included in this file.
//
//
//go:build freebsd || dragonfly || darwin
// +build freebsd dragonfly darwin
package tnet
import (
"errors"
"golang.org/x/sys/unix"
"trpc.group/trpc-go/tnet/internal/buffer"
"trpc.group/trpc-go/tnet/internal/cache/mcache"
"trpc.group/trpc-go/tnet/internal/netutil"
)
// FillToBuffer reads packets from UDP connection, and fills to buffer.
// If OS doesn't support UDP batch I/O, only one packet is received at a time.
func (nfd *netFD) FillToBuffer(b *buffer.Buffer) error {
block := mcache.Malloc(nfd.udpBufferSize + netutil.SockaddrSize)
n, sa, err := unix.Recvfrom(nfd.fd, block[netutil.SockaddrSize:], 0)
if err != nil {
if err == unix.EAGAIN || err == unix.EWOULDBLOCK {
return nil
}
return errors.New("failed to read UDP packet")
}
netutil.UnixSockaddrToSockaddrSlice(sa, block[:netutil.SockaddrSize])
if err != nil {
return err
}
b.Write(false, block[:netutil.SockaddrSize+n])
return nil
}
// SendPackets sends UDP packets from buffer.
// If OS doesn't support UDP batch I/O, only one packet is sent at a time
func (nfd *netFD) SendPackets(b *buffer.Buffer) error {
block := make([][]byte, 1)
n := b.PeekBlocks(block)
if n != 1 {
return errors.New("block numbers is unexpected")
}
buf, addr, err := getUDPDataAndAddr(block[0])
if err != nil {
return err
}
nfd.WriteTo(buf, addr)
return nil
}