本文整理匯總了Golang中net.ListenUDP函數的典型用法代碼示例。如果您正苦於以下問題:Golang ListenUDP函數的具體用法?Golang ListenUDP怎麽用?Golang ListenUDP使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了ListenUDP函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ListenAndServe
func ListenAndServe(addr string, port int) {
//addr_tcp, err := net.ResolveTCPAddr("tcp", l)
//if err != nil {
// panic(err)
//}
//listen_tcp, err := net.ListenTCP("tcp", addr_tcp)
//if err != nil {
// panic(err)
//}
//go tcp_listen(listen_tcp)
rtp_l := fmt.Sprintf("%v:%v", addr, port)
rtcp_l := fmt.Sprintf("%v:%v", addr, port+1)
addr1, err := net.ResolveUDPAddr("udp", rtp_l)
if err != nil {
panic(err)
}
listen_rtp, err := net.ListenUDP("udp", addr1)
if err != nil {
panic(err)
}
go udp_rtp_listen(listen_rtp)
addr2, err := net.ResolveUDPAddr("udp", rtcp_l)
if err != nil {
panic(err)
}
listen_rtcp, err := net.ListenUDP("udp", addr2)
if err != nil {
panic(err)
}
go udp_rtcp_listen(listen_rtcp)
}
示例2: main
func main() {
//測試手動注冊兩個通道
sip.GetChannel("10.2.42.197", "10.2.42.133")
sip.GetChannel("10.2.42.133", "10.2.42.197")
//鏈接WebRTC 服務
go webrtcSocket.Init()
//開啟出測地址
go sip.InitListener()
//監聽視頻端口
service := ":8088"
udpAddr, err := net.ResolveUDPAddr("udp", service)
checkError(err)
conn, err := net.ListenUDP("udp", udpAddr)
checkError(err)
fmt.Println("監聽端口")
for {
handleVideo(conn)
}
//監聽語音端口
go func() {
serviceAudio := ":11113"
udpAddrAudio, err := net.ResolveUDPAddr("udp", serviceAudio)
checkError(err)
connAudio, err := net.ListenUDP("udp", udpAddrAudio)
checkError(err)
for {
handleAudio(connAudio)
}
}()
}
示例3: Test_ContextCloseFuncWithConn
func Test_ContextCloseFuncWithConn(t *testing.T) {
time.Sleep(1 * time.Second)
testResult := make(chan error)
conns := make([]*net.UDPConn, 3)
for x := 0; x < 3; x++ {
a := net.UDPAddr{
IP: net.ParseIP("127.0.0.1"),
Port: 12345 + x,
}
c, err := net.ListenUDP("udp", &a)
if err != nil {
t.Fatal(err.Error())
}
conns[x] = c
}
ctx := NewContextWithConn(conns)
// Test done channel
testTimeout := time.After(200 * time.Millisecond)
go func() {
select {
case <-testTimeout:
errMsg := "Expect to close done channel"
testResult <- errors.New(errMsg)
case <-ctx.DoneChan:
testResult <- nil
}
}()
ctx.Done()
// Test if a connection not closed
for x := 0; x < 3; x++ {
a := net.UDPAddr{
IP: net.ParseIP("127.0.0.1"),
Port: 12345 + x,
}
c, err := net.ListenUDP("udp", &a)
if err != nil {
t.Fatal(err.Error())
}
err = c.Close()
if err != nil {
t.Fatal(err.Error())
}
}
err := <-testResult
if err != nil {
t.Fatal(err.Error())
}
time.Sleep(1 * time.Second)
}
示例4: Udp_init
func Udp_init(localListenPort, broadcastListenPort, message_size int, send_ch, receive_ch chan Udp_message) (err error) {
//Generating broadcast address
baddr, err = net.ResolveUDPAddr("udp4", "255.255.255.255:"+strconv.Itoa(broadcastListenPort))
if err != nil {
return err
}
//Generating localaddress
tempConn, err := net.DialUDP("udp4", nil, baddr)
defer tempConn.Close()
tempAddr := tempConn.LocalAddr()
laddr, err = net.ResolveUDPAddr("udp4", tempAddr.String())
laddr.Port = localListenPort
//Creating local listening connections
localListenConn, err := net.ListenUDP("udp4", laddr)
if err != nil {
return err
}
//Creating listener on broadcast connection
broadcastListenConn, err := net.ListenUDP("udp", baddr)
if err != nil {
localListenConn.Close()
return err
}
go udp_receive_server(localListenConn, broadcastListenConn, message_size, receive_ch)
go udp_transmit_server(localListenConn, broadcastListenConn, send_ch)
// fmt.Printf("Generating local address: \t Network(): %s \t String(): %s \n", laddr.Network(), laddr.String())
// fmt.Printf("Generating broadcast address: \t Network(): %s \t String(): %s \n", baddr.Network(), baddr.String())
return err
}
示例5: udpInit
func udpInit(localListenPort, broadcastListenPort, messageSize int, sendCh, receiveCh chan udpMessage) (err error) {
//Generating broadcast address
baddr, err = net.ResolveUDPAddr("udp4", "255.255.255.255:"+strconv.Itoa(broadcastListenPort))
if err != nil {
return err
}
//Generating localaddress
tempConn, err := net.DialUDP("udp4", nil, baddr)
defer tempConn.Close()
tempAddr := tempConn.LocalAddr()
laddr, err := net.ResolveUDPAddr("udp4", tempAddr.String())
laddr.Port = localListenPort
def.LocalIP = laddr.String()
//Creating local listening connections
localListenConn, err := net.ListenUDP("udp4", laddr)
if err != nil {
return err
}
//Creating listener on broadcast connection
broadcastListenConn, err := net.ListenUDP("udp", baddr)
if err != nil {
localListenConn.Close()
return err
}
udpConnection = true
go udpReceiveServer(localListenConn, broadcastListenConn, messageSize, receiveCh)
go udpTransmitServer(localListenConn, broadcastListenConn, sendCh)
return err
}
示例6: initSockets
func initSockets(BROADCAST_IP string, PORTNUM_COST string, PORTNUM_ORDER string) bool {
//Create broadcast socket for orders
broadcast_udp_addr, err := net.ResolveUDPAddr("udp", BROADCAST_IP+PORTNUM_ORDER)
if err != nil {
log.Println(" ResolveUDPAddr failed", err)
}
broadcast_order_conn, err := net.DialUDP("udp", nil, broadcast_udp_addr)
if err != nil {
log.Println("Could not establish UDP connection. Enter single eleveator mode. \n", err)
return false
}
broadcast_order_conn = broadcast_order_conn
//Create broadcast socket for cost updates
broadcast_udp_addr, err = net.ResolveUDPAddr("udp", BROADCAST_IP+PORTNUM_COST)
if err != nil {
log.Println("ResolveUDPAddr failed", err)
}
broadcast_cost_conn, err = net.DialUDP("udp", nil, broadcast_udp_addr)
if err != nil {
log.Println("Could not establish UDP connection. Enter single eleveator mode. \n", err)
return false
}
broadcast_cost_conn = broadcast_cost_conn
//Create receiver socket for external orders
listen_addr, err := net.ResolveUDPAddr("udp", PORTNUM_ORDER)
if err != nil {
log.Println("ResolveUDPAddr failed ", err)
}
receive_order_conn, err := net.ListenUDP("udp", listen_addr)
if err != nil {
log.Println("Could not establish UDP connection. Enter single eleveator mode. \n", err)
return false
}
receive_order_conn = receive_order_conn
//Create receiver socket for cost updates
listen_addr, err = net.ResolveUDPAddr("udp", PORTNUM_COST)
if err != nil {
log.Println("ResolveUDPAddr failed ", err)
}
receive_cost_conn, err := net.ListenUDP("udp", listen_addr)
if err != nil {
log.Println("Could not establish UDP connection. Enter single eleveator mode.\n", err)
return false
}
receive_cost_conn = receive_cost_conn
return true
}
示例7: Dial
func Dial(remote string) (*UDPSession, error) {
// defer SavePanic()
//log.Println("Dial")
remoteAddr, err := net.ResolveUDPAddr("udp", remote)
if err != nil {
return nil, err
}
tmpSock, _err := net.ListenUDP("udp", nil)
if _err != nil {
return nil, _err
}
// 必須新建一個 否則服務端新socket發送過來的數據 會直接被丟棄 接收不到
localSock, _err := net.ListenUDP("udp", nil)
if _err != nil {
return nil, _err
}
localAddr := localSock.LocalAddr().(*net.UDPAddr)
//buf := make([]byte, 1500) //udp包大小不超過1400
wbuf := make([]byte, 5)
buf := make([]byte, 5)
wbuf[0] = CmdCreateSession
binary.LittleEndian.PutUint32(wbuf[1:], uint32(localAddr.Port))
for j := 0; j < 20; j = j + 1 {
tmpSock.WriteTo(wbuf, remoteAddr)
tmpSock.SetReadDeadline(time.Now().Add(300 * time.Millisecond))
n, from, err := tmpSock.ReadFromUDP(buf)
if n >= len(buf) && from.String() == remoteAddr.String() {
if buf[0] == CmdCreateSessionRsp {
//log.Println("CmdCreateSessionRsp")
tmpSock.Close()
newAddr := net.UDPAddr{
IP: from.IP,
Port: int(binary.LittleEndian.Uint32(buf[1:])),
}
session := newUDPSession(nil, &newAddr, localSock, localAddr)
go session.readLoop()
go session.updateLoop()
return session, nil
}
}
if n < 0 {
//log.Println("dial: n < 0 ")
tmpSock.Close()
localSock.Close()
return nil, err
}
}
tmpSock.Close()
localSock.Close()
return nil, errors.New("dial: no response")
}
示例8: Init
/*
This function initializes the UDP module. It sets the port for listening, broadcasting, the approved message size and the channels
for communicating with the calling module. It returns the local IP-address of this system/module, and an error if if it fails(then ip is "").
*/
func Init(localListenPort, broadcastListenPort, messageSize int, sendChannel <-chan UDPMessage, receiveChannel chan<- UDPMessage) (localIP string, err error) {
// Generate broadcast address
broadcastAdress, err = net.ResolveUDPAddr(udp4, broadcastIp+strconv.Itoa(broadcastListenPort))
if err != nil {
log.Println("UDP:\t Could not resolve UDPAddress.")
return "", err
} else if debug {
// We are in debug mode.
log.Printf("UDP:\t Generating broadcast address:\t %s \n", broadcastAdress.String())
}
// Generate local address, uses the tempConnection to fetch address via the UDP dial.
tempConnection, err := net.DialUDP(udp4, nil, broadcastAdress)
if err != nil {
log.Println("UDP:\t No network connection")
return "", err
}
defer tempConnection.Close() // Makes sure the connection is closed when Init completes.
tempAddress := tempConnection.LocalAddr()
localAddress, err = net.ResolveUDPAddr(udp4, tempAddress.String())
if err != nil {
log.Println("UDP:\t Could not resolve local address.")
return "", err
} else if debug {
log.Printf("UDP:\t Generating local address: \t%s \n", localAddress.String())
}
localAddress.Port = localListenPort // Set the port property of the *net.UDPAddr struct
// Create local listening connections
localListenConnection, err := net.ListenUDP(udp4, localAddress) // Listens for incoming UDP packets addressed to localAddress.
if err != nil {
log.Println("UDP:\t Couldn't create a UDP listener socket.")
return "", err
}
if debug {
log.Println("UDP:\t Created a UDP listener socket.")
}
// Create a listener on broadcast connection.
broadcastListenConnection, err := net.ListenUDP(udp4, &net.UDPAddr{IP: net.IPv4(0, 0, 0, 0), Port: broadcastListenPort})
if err != nil {
log.Println("UDP:\t Could not create a UDP broadcast listen socket.")
localListenConnection.Close()
return "", err
}
if debug {
log.Println("UDP:\t Created a UDP broadcast listen socket.")
}
// Start goroutines to handle incoming messages and sending outgoing messages.
go udpReceiveServer(localListenConnection, broadcastListenConnection, messageSize, receiveChannel)
go udpTransmitServer(localListenConnection, broadcastListenConnection, localListenPort, broadcastListenPort, sendChannel)
return localAddress.IP.String(), err
}
示例9: TestSecureUdp
func TestSecureUdp(t *testing.T) {
data := []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}
port := ":0"
udpAddr, err := net.ResolveUDPAddr("udp", port)
if err != nil {
t.Fatal(err)
}
ln, err := net.ListenUDP("udp", udpAddr)
if err != nil {
t.Fatal(err)
}
Addr := ln.LocalAddr()
defer ln.Close()
cipher, err := NewCipher("aes-256-cfb", "password")
if err != nil {
t.Fatal(err)
}
go func() {
secureConn := NewPacketConn(ln, cipher.Copy())
buf := make([]byte, 1500)
n, src, err := secureConn.ReadFrom(buf)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(buf[:n], data) {
t.Error("UDP server recieved data does not match.")
}
_, err = secureConn.WriteTo(buf[:n], src)
if err != nil {
t.Fatal(err)
}
return
}()
time.Sleep(100 * time.Millisecond)
ln2, err := net.ListenUDP("udp", udpAddr)
if err != nil {
t.Fatal(err)
}
secureconn := NewPacketConn(ln2, cipher.Copy())
_, err = secureconn.WriteTo(data, Addr)
if err != nil {
t.Fatal(err)
}
buf := make([]byte, 1500)
n, _, err := secureconn.ReadFrom(buf)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(buf[:n], data) {
t.Error("UDP client read does not match.")
}
}
示例10: newServer
// Constructs server structure
func newServer(iface *net.Interface) (*Server, error) {
// Create wildcard connections (because :5353 can be already taken by other apps)
ipv4conn, err := net.ListenUDP("udp4", mdnsWildcardAddrIPv4)
if err != nil {
log.Printf("[ERR] bonjour: Failed to bind to udp4 port: %v", err)
}
ipv6conn, err := net.ListenUDP("udp6", mdnsWildcardAddrIPv6)
if err != nil {
log.Printf("[ERR] bonjour: Failed to bind to udp6 port: %v", err)
}
if ipv4conn == nil && ipv6conn == nil {
return nil, fmt.Errorf("[ERR] bonjour: Failed to bind to any udp port!")
}
// Join multicast groups to receive announcements
p1 := ipv4.NewPacketConn(ipv4conn)
p2 := ipv6.NewPacketConn(ipv6conn)
if iface != nil {
if err := p1.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil {
return nil, err
}
if err := p2.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil {
return nil, err
}
} else {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
errCount1, errCount2 := 0, 0
for _, iface := range ifaces {
if err := p1.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil {
errCount1++
}
if err := p2.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil {
errCount2++
}
}
if len(ifaces) == errCount1 && len(ifaces) == errCount2 {
return nil, fmt.Errorf("Failed to join multicast group on all interfaces!")
}
}
s := &Server{
ipv4conn: ipv4conn,
ipv6conn: ipv6conn,
ttl: 3200,
}
return s, nil
}
示例11: newClient
// Client structure constructor
func newClient(iface *net.Interface, serviceChan chan<- *ServiceEntry) (*client, error) {
// Create wildcard connections (because :5353 can be already taken by other apps)
ipv4conn, err := net.ListenUDP("udp4", mdnsWildcardAddrIPv4)
if err != nil {
log.Printf("[ERR] bonjour: Failed to bind to udp4 port: %v", err)
}
ipv6conn, err := net.ListenUDP("udp6", mdnsWildcardAddrIPv6)
if ipv4conn == nil && ipv6conn == nil {
return nil, fmt.Errorf("[ERR] bonjour: Failed to bind to any udp port!")
}
// Join multicast groups to receive announcements from server
p1 := ipv4.NewPacketConn(ipv4conn)
p2 := ipv6.NewPacketConn(ipv6conn)
if iface != nil {
if err := p1.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil {
return nil, err
}
if err := p2.JoinGroup(iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil {
return nil, err
}
} else {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
errCount1, errCount2 := 0, 0
for _, iface := range ifaces {
if err := p1.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv4}); err != nil {
errCount1++
}
if err := p2.JoinGroup(&iface, &net.UDPAddr{IP: mdnsGroupIPv6}); err != nil {
errCount2++
}
}
if len(ifaces) == errCount1 && len(ifaces) == errCount2 {
return nil, fmt.Errorf("Failed to join multicast group on all interfaces!")
}
}
c := &client{
lookupParams: make(map[string]*LookupParams),
serviceChan: serviceChan,
ipv4conn: ipv4conn,
ipv6conn: ipv6conn,
closedCh: make(chan bool),
}
return c, nil
}
示例12: ListenOnTransports
// ListenOnTransports listens for incoming RTP and RTCP packets addressed
// to this transport.
//
func (tp *TransportUDP) ListenOnTransports() (err error) {
tp.dataConn, err = net.ListenUDP(tp.localAddrRtp.Network(), tp.localAddrRtp)
if err != nil {
return
}
tp.ctrlConn, err = net.ListenUDP(tp.localAddrRtcp.Network(), tp.localAddrRtcp)
if err != nil {
tp.dataConn.Close()
tp.dataConn = nil
return
}
go tp.readDataPacket()
go tp.readCtrlPacket()
return nil
}
示例13: InitSendService
func InitSendService(speed int64, from string, to string) (service *SendService, err error) {
service = new(SendService)
service.speed = speed
addr, err := net.ResolveUDPAddr("udp4", from)
if err != nil {
return nil, err
}
service.addr, err = net.ResolveUDPAddr("udp4", to)
if err != nil {
return nil, err
}
service.conn, err = net.ListenUDP("udp4", addr)
if err != nil {
return nil, err
}
// conn, err := net.Dial("udp", "127.0.0.1:12345")
// if err != nil {
// panic(err)
// }
// service.conn = conn
return service, nil
}
示例14: NewDiscoverer
func NewDiscoverer(id string, port int, extPort int, extServer string) (*Discoverer, error) {
local4 := &net.UDPAddr{IP: net.IP{0, 0, 0, 0}, Port: AnnouncementPort}
conn, err := net.ListenUDP("udp4", local4)
if err != nil {
return nil, err
}
disc := &Discoverer{
MyID: id,
ListenPort: port,
BroadcastIntv: 30 * time.Second,
ExtListenPort: extPort,
ExtBroadcastIntv: 1800 * time.Second,
conn: conn,
registry: make(map[string]string),
extServer: extServer,
}
go disc.recvAnnouncements()
if disc.ListenPort > 0 {
disc.sendAnnouncements()
}
if len(disc.extServer) > 0 && disc.ExtListenPort > 0 {
disc.sendExtAnnouncements()
}
return disc, nil
}
示例15: Listen
// Listen creates a UDP server that parses statsd data into metrics and
// sends them over a channel.
func Listen(addr string, c chan Packet, clean bool) {
cleaner := NewCleaner()
laddr, err := net.ResolveUDPAddr("udp", addr)
if err != nil {
log.Fatalln("fatal: failed to resolve address", err)
}
conn, err := net.ListenUDP("udp", laddr)
if err != nil {
log.Fatalln("fatal: failed to listen", err)
}
for {
buf := make([]byte, 1452)
n, raddr, err := conn.ReadFrom(buf[:])
t := time.Now().UTC()
if err != nil {
log.Println("error: Failed to recieve packet", err)
} else {
metrics, err := Parse(buf[0:n])
if err != nil {
log.Println("error: Failed to recieve packet", err)
}
if metrics != nil {
var p Packet
if clean {
cleaned := cleaner.CleanMetrics(*metrics)
p = Packet{&cleaned, raddr, t}
} else {
p = Packet{metrics, raddr, t}
}
c <- p
}
}
}
}