gpt4 book ai didi

go - 一次进行udp连接拨号,然后发送许多

转载 作者:行者123 更新时间:2023-12-01 22:28:30 25 4
gpt4 key购买 nike

请在下面考虑此代码,它是服务的简化版本。我推出了在其生命周期内需要使用goroutine,并且在进行操作时,需要将udp消息发送到设置的目的地。

package main

import (
"fmt"
"log"
"net"
"time"
)

const (
udp_dest = "192.168.1.200:514"
)

func main() {
fmt.Println("Hello")
message := "this is a test"
log_message(&message)
go worker(1)
go worker(2)
go worker(3)
go worker(4)
time.Sleep(3009 * time.Second)
}

func log_message(message *string) {
RemoteAddr, err := net.ResolveUDPAddr("udp", udp_dest)
if err != nil {
//fmt.Println("Err, net.ResolveUDPAddr", err)
return
}
conn, err := net.DialUDP("udp", nil, RemoteAddr)
if err != nil {
return
}
udp_message := fmt.Sprintf("<30> %s", *message)
Bytes, _ := conn.Write([]byte(udp_message))
log.Printf("Sent %d Bytes to %s\n", Bytes, udp_dest)
}

func worker(tag int) {
i := 0
for {
worker_message := fmt.Sprintf("Some message from worker%d, loop: %d", tag, i)
log_message(&worker_message)
// do some work..
time.Sleep(300 * time.Second)
i += 1
}
}

在我的 log_message中,每次调用它时,我们都在调用 net.DialUDP,我觉得这很浪费。我尝试使用 &net.UDPConn等全局变量进行实验,但无法正常工作。

请说明如何实现/优化此功能?只有一个UDP目标,我希望守护程序在启动时先进行一次 Dial,然后根据需要仅进行 Write

谢谢!

这是到目前为止我得到的:
package main

import (
"fmt"
"log"
"net"
"time"
)

const (
udp_dest = "192.168.1.200:514"
)

var (
myconn *net.UDPConn
)

func main() {
fmt.Println("Hello")
message := "this is a test"
log_message(&message)
go worker(1)
go worker(2)
go worker(3)
go worker(4)
time.Sleep(3009 * time.Second)
}

func log_message(message *string) {

if myconn == nil {

fmt.Println("Setting up myconn!")
RemoteAddr, err := net.ResolveUDPAddr("udp", udp_dest)
if err != nil {
//fmt.Println("Err, net.ResolveUDPAddr", err)
return
}
myconn, err = net.DialUDP("udp", nil, RemoteAddr)

if err != nil {
return
}
}

udp_message := fmt.Sprintf("<30> %s", *message)
Bytes, _ := myconn.Write([]byte(udp_message))
log.Printf("Sent %d Bytes to %s\n", Bytes, udp_dest)
}

func worker(tag int) {
i := 0
for {
worker_message := fmt.Sprintf("Some message from worker%d, loop: %d", tag, i)
log_message(&worker_message)
// do some work..
time.Sleep(10 * time.Second)
i += 1
}
}

最佳答案

你快到了。在启动goroutines之前,将设置代码移至一个函数并调用它。

func main() {
if err := setupLog(); err != nil {
log.Fatal(err)
}
fmt.Println("Hello")
... same as before
}

func setupLog() error {
fmt.Println("Setting up myconn!")
RemoteAddr, err := net.ResolveUDPAddr("udp", udp_dest)
if err != nil {
return err
}
myconn, err = net.DialUDP("udp", nil, RemoteAddr)
return err
}

func log_message(message *string) {
udp_message := fmt.Sprintf("<30> %s", *message)
Bytes, _ := myconn.Write([]byte(udp_message))
log.Printf("Sent %d Bytes to %s\n", Bytes, udp_dest)
}

问题中的代码不起作用,因为 myconn上存在数据争用。

关于go - 一次进行udp连接拨号,然后发送许多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58291508/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com