本文整理汇总了Golang中net.DialUDP函数的典型用法代码示例。如果您正苦于以下问题:Golang DialUDP函数的具体用法?Golang DialUDP怎么用?Golang DialUDP使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了DialUDP函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: 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
}
示例2: TestExchange3
func TestExchange3(t *testing.T) {
m := &Message{}
m.Header.ID = GenID()
m.Question.STAR("google.com", rr.CLASS_IN)
m.RD = true
m2 := &Message{}
m2.Header.ID = GenID()
m2.Question.STAR("google.cz", rr.CLASS_IN)
m2.RD = true
addr, err := net.ResolveUDPAddr("udp", "8.8.8.8:53")
if err != nil {
t.Fatal(err)
}
c, err := net.DialUDP("udp", nil, addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
addr, err = net.ResolveUDPAddr("udp", "8.8.4.4:53")
if err != nil {
t.Error(err)
return
}
c.SetDeadline(time.Now().Add(5 * time.Second))
c2, err := net.DialUDP("udp", nil, addr)
if err != nil {
t.Error(err)
return
}
defer c2.Close()
c2.SetDeadline(time.Now().Add(5 * time.Second))
ch := m.GoExchange(c, 2000, m2.GoExchange(c2, 2000, nil))
re := <-ch
if re.error != nil {
t.Error(re.error)
return
}
t.Log(re.Message)
re = <-ch
if re.error != nil {
t.Error(40, re.error)
return
}
t.Log(re.Message)
}
示例3: ServeServerList
func ServeServerList(rw http.ResponseWriter, req *http.Request) {
addr, _ := net.ResolveUDPAddr("udp", "hl2master.steampowered.com:27011")
conn, _ := net.DialUDP("udp", nil, addr)
defer conn.Close()
conn.Write([]byte("\x31\xFF0.0.0.0:0\x00\\appid\\225600\\gamedir\\berimbau\\empty\\1\x00"))
buf := make([]byte, 512)
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
readBytes, err := conn.Read(buf)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
var srvs []Server
i := 6
for i+6 < readBytes {
srv := Server{}
srv.Address = net.IPv4(buf[i], buf[i+1], buf[i+2], buf[i+3])
srv.Port = uint16(buf[i+4])<<8 + uint16(buf[i+5])
addr, _ = net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", srv.Address.String(), srv.Port))
conn, _ = net.DialUDP("udp", nil, addr)
defer conn.Close()
conn.Write([]byte("\xFF\xFF\xFF\xFF\x54Source Engine Query\x00"))
srvbuf := make([]byte, 512)
conn.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
srvReadBytes, err := conn.Read(srvbuf)
_ = srvReadBytes
if err != nil {
log.Println(err)
i += 6
continue
}
curIndex := 6
srv.Name = getString(srvbuf, curIndex)
curIndex += len(srv.Name) + 1
srv.Map = getString(srvbuf, curIndex)
curIndex += len(srv.Map) + 1
curIndex += len(getString(srvbuf, curIndex)) + 1 //skip folder
curIndex += len(getString(srvbuf, curIndex)) + 1 //skip game
curIndex += 2 //skip gameid
srv.PlayerCount = srvbuf[curIndex]
srv.Capacity = srvbuf[curIndex+1]
srvs = append(srvs, srv)
i += 6
}
sort.Sort(Servers(srvs))
rw.Header().Add("content-type", "text/html; charset=utf-8")
tpl.Execute(rw, srvs)
return
}
示例4: main
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.Println("Version: 1.0")
var passer msgpasser.Passer
passer.Init(9999)
time.Sleep(3 * time.Second)
for i, addrS := range addrs {
addr, _ := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:9999", addrS))
conn, _ := net.DialUDP("udp", nil, addr)
data := msgpasser.GameRoomData{"game room info", 0, nil, len(names), names[i], "join", localName}
data.Players = make([]msgpasser.PlayerInfo, len(names))
for i := range names {
data.Players[i].Ip = addrs[i]
data.Players[i].Name = names[i]
}
b, err := json.Marshal(&data)
log.Println(string(b))
if err != nil {
log.Println(err)
}
_, err = conn.Write(b)
if err != nil {
log.Println(err)
}
}
addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:9999")
conn, _ := net.DialUDP("udp", nil, addr)
// To avoid too many input happen
time.Sleep(3 * time.Second)
x := 10000
y := 3
for i := 0; i < x; i++ {
for j := 0; j < y; j++ {
msg := msgpasser.Data{fmt.Sprintf("%v %d", localName, i*y+j), true}
b, _ := json.Marshal(&msg)
conn.Write(b)
}
time.Sleep(300 * time.Millisecond)
}
for {
time.Sleep(30 * time.Second)
log.Println("I am still alive!")
}
}
示例5: main
func main() {
var statsdHost = flag.String("statsd_host", "127.0.0.1", "Statsd host")
var statsdPort = flag.Int("statsd_port", 8125, "Statsd host")
var nodename = flag.String("nodename", "riak", "Riak node name")
var riakHost = flag.String("riak_host", "127.0.0.1", "Riak host")
var riakHttpPort = flag.Int("riak_http_port", 8098, "Riak HTTP port")
flag.Parse()
// First ping to node to make sure it works
err := pingRiak(*riakHost, *riakHttpPort)
if err != nil {
log.Fatalf("Error: %v", err)
os.Exit(1)
}
statsd := fmt.Sprintf("%s:%d", *statsdHost, *statsdPort)
addr, err := net.ResolveUDPAddr("udp", statsd)
if err != nil {
log.Fatalf("Couldn't resolve UDP addr: %v", err)
os.Exit(1)
}
conn, err := net.DialUDP("udp", nil, addr)
if err != nil {
log.Fatalf("Couldn't connect to statsd at %s", statsd)
os.Exit(1)
}
// every 60s run hit the stats endpoint and then send to statsd
interval := time.NewTicker(time.Second * 60)
for _ = range interval.C {
go getAndSendRiakMetrics(conn, *nodename, *riakHost, *riakHttpPort)
}
}
示例6: doProxyClientDNS
func doProxyClientDNS(reqData []byte, client *net.UDPAddr) []byte {
conn, err := net.DialUDP("udp", nil, server)
if err != nil {
fmt.Fprintf(os.Stderr, "Can't dial server: %v\n", err)
os.Exit(1)
}
defer conn.Close()
_, err = conn.Write(reqData)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to write to server: %v\n", err)
return nil
}
t := time.Now().Add(time.Duration(5) * time.Second)
conn.SetReadDeadline(t)
var rep []byte
for {
repData := make([]byte, 2048)
nr, err := conn.Read(repData)
if err != nil {
err2, ok := err.(*net.OpError)
if ok && err2.Timeout() {
break
}
fmt.Fprintf(os.Stderr, "Failed to read from server: %v\n", err)
break
}
rep = repData[:nr]
}
return rep
}
示例7: sendImAlive
func sendImAlive() {
service := broadcast + ":" + UDPport
addr, err := net.ResolveUDPAddr("udp4", service)
if err != nil {
fmt.Println("net.ResolveUDPAddr error in sendImAlive: ", err)
internal.setupFail <- true
}
isalivesocket, err := net.DialUDP("udp4", nil, addr)
if err != nil {
fmt.Println("net.DialUDP error in sendImAlive: ", err)
internal.setupFail <- true
}
isAliveMessage := []byte("ping")
for {
select {
case <-internal.quitsendImAlive:
return
default:
_, err := isalivesocket.Write(isAliveMessage)
if err != nil {
fmt.Println("Write error in sendImAlive: ", err)
}
time.Sleep(sleepduration * time.Millisecond)
}
}
}
示例8: SendMagicPacket
func SendMagicPacket(macAddr string, bcastAddr string, bcastPort string) error {
if len(macAddr) != (6*2 + 5) {
return errors.New("Invalid MAC Address String: " + macAddr)
}
packet, err := constructMagicPacket(macAddr)
if err != nil {
return err
}
a, err := net.ResolveUDPAddr("udp", bcastAddr+":"+bcastPort)
if err != nil {
return err
}
c, err := net.DialUDP("udp", nil, a)
if err != nil {
return err
}
written, err := c.Write(packet)
c.Close()
// Packet must be 102 bytes in length
if written != 102 {
return err
}
return nil
}
示例9: Dial
func Dial(dest v2net.Destination) (net.Conn, error) {
var ip net.IP
if dest.Address().IsIPv4() || dest.Address().IsIPv6() {
ip = dest.Address().IP()
} else {
ips, err := net.LookupIP(dest.Address().Domain())
if err != nil {
return nil, err
}
if len(ips) == 0 {
return nil, ErrInvalidHost
}
ip = ips[dice.Roll(len(ips))]
}
if dest.IsTCP() {
return net.DialTCP("tcp", nil, &net.TCPAddr{
IP: ip,
Port: int(dest.Port()),
})
} else {
return net.DialUDP("udp", nil, &net.UDPAddr{
IP: ip,
Port: int(dest.Port()),
})
}
}
示例10: udp_init
func udp_init() (err error) {
//Generating broadcast address
baddr, err = net.ResolveUDPAddr("udp4", "255.255.255.255:"+strconv.Itoa(30000))
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 = 30000 //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, 1024, 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
}
示例11: sender
func (logstash *Logstash) sender() {
for {
ServerAddress, err := net.ResolveUDPAddr("udp", logstash.Address)
if err != nil {
logger.Error("Can't resolve remote UDP address: %s", err.Error())
} else {
Conn, err := net.DialUDP("udp", nil, ServerAddress)
if err != nil {
logger.Error("Can't dial up: %s", err.Error())
} else {
logger.Notice("Connected to remote UDP address: %s", ServerAddress.String())
for {
select {
case message := <-logstash.channel:
if *debug {
logger.Debug(fmt.Sprintf("Writing to UDP socket: %s", message))
}
_, err := Conn.Write([]byte(message))
if err != nil {
logger.Error("Can't write: %s", err.Error())
Conn.Close()
goto RETRY
}
}
}
}
}
RETRY:
time.Sleep(retryTimeout)
}
}
示例12: udpClient
// Udp client which sends a fixed num of packets to given port after a fixed delay.
// Delay ensures that capture code is ready to recv packets.
func udpClient(port int, numPkts int, wait time.Duration, t *testing.T) {
time.Sleep(wait)
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
t.Logf("ERROR Failed to resolve udp addr err:%s", err)
return
}
conn, err := net.DialUDP("udp", nil, addr)
if err != nil {
t.Logf("ERROR Failed to dial udp port:%d err:%s", port, err)
return
}
t.Logf("Start packets to port:%d", port)
pkt := []byte("hello")
for i := 0; i < numPkts; i++ {
if l, err := conn.Write(pkt); err != nil || l != len(pkt) {
t.Logf("ERROR Failed to send packet size:%d wlen:%d err:%s", len(pkt), l, err)
}
}
t.Logf("Completed sending packets to port:%d", port)
}
示例13: NewUdpProxy
func NewUdpProxy(listenAddr, targetAddr string) (*UdpProxy, error) {
var listenUDP, targetUDP *net.UDPAddr
var err error
if listenUDP, err = net.ResolveUDPAddr("udp", listenAddr); err != nil {
return nil, err
}
if targetUDP, err = net.ResolveUDPAddr("udp", targetAddr); err != nil {
return nil, err
}
listenConn, err := net.ListenUDP("udp", listenUDP)
if err != nil {
return nil, err
}
// TODO http://play.golang.org/p/ygGFr9oLpW
// for per-UDP-packet addressing in case one proxy handles multiple connections
targetConn, err := net.DialUDP("udp", nil, targetUDP)
if err != nil {
listenConn.Close()
return nil, err
}
return &UdpProxy{
listenConn: listenConn,
listenAddr: listenUDP,
targetConn: targetConn,
targetAddr: targetUDP,
packets: make(chan []byte, BufferedPackets),
proxyClosed: golib.NewOneshotCondition(),
writeErrors: make(chan error, buf_write_errors),
Stats: stats.NewStats("UDP Proxy " + listenAddr),
OnError: OnErrorClose,
writePausedCond: sync.Cond{L: new(sync.Mutex)},
}, nil
}
示例14: TestExchange2
func TestExchange2(t *testing.T) {
m := &Message{}
m.Header.ID = GenID()
m.Question.NS("google.com", rr.CLASS_IN)
ch := make(ExchangeChan, 10)
addr, err := net.ResolveUDPAddr("udp", "8.8.8.8:53")
if err != nil {
t.Fatal(err)
}
c, err := net.DialUDP("udp", nil, addr)
if err != nil {
t.Fatal(10, err)
}
defer c.Close()
c.SetDeadline(time.Now().Add(5 * time.Second))
re := <-m.GoExchange(c, 2000, ch)
if re.error != nil {
t.Fatal(20, re.error)
}
t.Log(re.Message)
}
示例15: TestExchange1
func TestExchange1(t *testing.T) {
m := &Message{}
m.Header.ID = GenID()
m.Question.A("localhost", rr.CLASS_IN)
ch := make(ExchangeChan, 10)
addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:7")
if err != nil {
t.Fatal(err)
}
c, err := net.DialUDP("udp", nil, addr)
if err != nil {
t.Fatal(10, err)
}
defer c.Close()
c.SetDeadline(time.Now().Add(time.Millisecond))
re := <-m.GoExchange(c, 2000, ch)
if re.error == nil {
t.Fatal(20)
}
t.Log(20, re.error)
}