当前位置: 首页>>代码示例>>Golang>>正文


Golang UDPConn.ReadFromUDP方法代码示例

本文整理汇总了Golang中net.UDPConn.ReadFromUDP方法的典型用法代码示例。如果您正苦于以下问题:Golang UDPConn.ReadFromUDP方法的具体用法?Golang UDPConn.ReadFromUDP怎么用?Golang UDPConn.ReadFromUDP使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net.UDPConn的用法示例。


在下文中一共展示了UDPConn.ReadFromUDP方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: handleClient

//----------------------------------------------- handle cooldown request
func handleClient(conn *net.UDPConn) {
	// init receive buffer
	config := cfg.Get()
	maxchan, e := strconv.Atoi(config["stats_max_queue_size"])
	if e != nil {
		maxchan = DEFAULT_MAX_QUEUE
		log.Println("cannot parse stats_max_queue_size from config", e)
	}

	ch := make(chan []byte, maxchan)
	defer close(ch)

	go StatsAgent(ch, conn)

	// loop receiving
	for {
		// udp receive buffer, max 512 packet
		data := make([]byte, 512)
		n, addr, err := conn.ReadFromUDP(data)
		if err != nil {
			log.Println("read udp failed", n, addr, err)
			continue
		}

		ch <- data[:n]
	}
}
开发者ID:hycxa,项目名称:gonet,代码行数:28,代码来源:main.go

示例2: udpReader

func (router *Router) udpReader(conn *net.UDPConn, po PacketSink) {
	defer conn.Close()
	dec := NewEthernetDecoder()
	handleUDPPacket := router.handleUDPPacketFunc(dec, po)
	buf := make([]byte, MaxUDPPacketSize)
	for {
		n, sender, err := conn.ReadFromUDP(buf)
		if err == io.EOF {
			return
		} else if err != nil {
			log.Println("ignoring UDP read error", err)
			continue
		} else if n < NameSize {
			continue // TODO something different?
		} else {
			name := PeerNameFromBin(buf[:NameSize])
			packet := make([]byte, n-NameSize)
			copy(packet, buf[NameSize:n])
			udpPacket := &UDPPacket{
				Name:   name,
				Packet: packet,
				Sender: sender}
			peerConn, found := router.Ourself.ConnectionTo(name)
			if !found {
				continue
			}
			relayConn, ok := peerConn.(*LocalConnection)
			if !ok {
				continue
			}
			checkWarn(relayConn.Decryptor.IterateFrames(handleUDPPacket, udpPacket))
		}
	}
}
开发者ID:adieu,项目名称:weave,代码行数:34,代码来源:router.go

示例3: ServeUDP

// ServeUDP starts a UDP listener for the server.
// Each request is handled in a seperate goroutine,
// with the Handler set in ....
func (srv *Server) ServeUDP(l *net.UDPConn) error {
	defer l.Close()
	handler := srv.Handler
	if handler == nil {
		handler = DefaultServeMux
	}
	if srv.UDPSize == 0 {
		srv.UDPSize = UDPMsgSize
	}
	for {
		m := make([]byte, srv.UDPSize)
		n, a, e := l.ReadFromUDP(m)
		if e != nil {
			return e
		}
		m = m[:n]

		if srv.ReadTimeout != 0 {
			l.SetReadDeadline(time.Now().Add(srv.ReadTimeout))
		}
		if srv.WriteTimeout != 0 {
			l.SetWriteDeadline(time.Now().Add(srv.WriteTimeout))
		}
		d, err := newConn(nil, l, a, m, handler, srv.TsigSecret)
		if err != nil {
			continue
		}
		go d.serve()
	}
	panic("not reached")
}
开发者ID:h2non,项目名称:dns,代码行数:34,代码来源:server.go

示例4: readFromSocket

// Read from UDP socket, writes slice of byte into channel.
func readFromSocket(socket *net.UDPConn, conChan chan packetType, bytesArena arena, stop chan bool) {
	for {
		b := bytesArena.Pop()
		n, addr, err := socket.ReadFromUDP(b)
		if err != nil {
			log.V(3).Infof("DHT: readResponse error:", err)
		}
		b = b[0:n]
		if n == maxUDPPacketSize {
			log.V(3).Infof("DHT: Warning. Received packet with len >= %d, some data may have been discarded.\n", maxUDPPacketSize)
		}
		totalReadBytes.Add(int64(n))
		if n > 0 && err == nil {
			p := packetType{b, *addr}
			select {
			case conChan <- p:
				continue
			case <-stop:
				return
			}
		}
		// Do a non-blocking read of the stop channel and stop this goroutine if the channel
		// has been closed.
		select {
		case <-stop:
			return
		default:
		}
	}
}
开发者ID:kissthink,项目名称:dht,代码行数:31,代码来源:krpc.go

示例5: UDPInbox

func UDPInbox(ctx Context, conn *net.UDPConn, buf int) (chan UDPPacket, error) {
	udpIn := make(chan UDPPacket, buf)
	go func() {
		for {
			payload := make([]byte, MaxUDPPacketSize)

			size, rAddr, err := conn.ReadFromUDP(payload)
			if err != nil {
				// Check if the done channel closed then shutdown goroutine
				select {
				case <-ctx.DoneChan:
					ctx.Log.Debug.Println("UDPInbox shutdown")
					close(udpIn)
					return
				default:
					// Need default case otherwise the select statment would block
				}

				ctx.Log.Error.Println(err.Error())
				continue
			}
			ctx.Log.Debug.Println("Receive UDP Packet")
			udpIn <- UDPPacket{
				RemoteAddr: rAddr,
				Size:       size,
				Payload:    payload,
			}

		}

	}()
	return udpIn, nil
}
开发者ID:rrawrriw,项目名称:ite,代码行数:33,代码来源:client.go

示例6: listen

func listen(socket *net.UDPConn) {
	data := make([]byte, 4096)
	length, remoteAddr, err := socket.ReadFromUDP(data)
	if err != nil {
		log.Fatal(err)
	}

	//@ToDO: Check, if the user wants the file
	var request transmitFileRequest
	error := json.Unmarshal(data[:length], &request)
	if error != nil {
		log.Fatal(error)
	}

	fmt.Printf("Got connection attempt from %s -> ", remoteAddr)

	//Only accept connections from server when the user specified it
	if *server != nil {
		if remoteAddr.IP.Equal(*server) {
			fmt.Printf("accepting connection\n")
			fmt.Printf("Remote wants to transfer %s (Size: %s)\n", request.FileName, humanize.Bytes(uint64(request.Size)))
			acceptIncomingFileTransfer(remoteAddr.IP, request)
		} else {
			fmt.Printf("DENY (only accepting connections from %s)", *server)
		}
	} else {
		fmt.Printf("accepting connection\n")
		fmt.Printf("Remote wants to transfer %s (Size: %s)\n", request.FileName, humanize.Bytes(uint64(request.Size)))
		acceptIncomingFileTransfer(remoteAddr.IP, request)
	}
}
开发者ID:jannickfahlbusch,项目名称:magic-filetransfer,代码行数:31,代码来源:incoming.go

示例7: AcceptPackets

func (handler *VMessInboundHandler) AcceptPackets(conn *net.UDPConn) {
	for {
		buffer := make([]byte, bufferSize)
		nBytes, addr, err := conn.ReadFromUDP(buffer)
		if err != nil {
			log.Error("VMessIn failed to read UDP packets: %v", err)
			continue
		}

		reader := bytes.NewReader(buffer[:nBytes])
		requestReader := protocol.NewVMessRequestReader(handler.clients)

		request, err := requestReader.Read(reader)
		if err != nil {
			log.Warning("VMessIn: Invalid request from (%s): %v", addr.String(), err)
			continue
		}

		cryptReader, err := v2io.NewAesDecryptReader(request.RequestKey, request.RequestIV, reader)
		if err != nil {
			log.Error("VMessIn: Failed to create decrypt reader: %v", err)
			continue
		}

		data := make([]byte, bufferSize)
		nBytes, err = cryptReader.Read(data)
		if err != nil {
			log.Warning("VMessIn: Unable to decrypt data: %v", err)
			continue
		}

		packet := v2net.NewPacket(request.Destination(), data[:nBytes], false)
		go handler.handlePacket(conn, request, packet, addr)
	}
}
开发者ID:kkndyu,项目名称:v2ray-core,代码行数:35,代码来源:vmessin_udp.go

示例8: detect_precense

func detect_precense(connection *net.UDPConn, masterChan chan bool) {
	buffer := make([]byte, 2048)
	for {
		t := time.Now()
		connection.SetReadDeadline(t.Add(3 * time.Second))
		_, _, err := connection.ReadFromUDP(buffer)
		if err != nil {
			fmt.Println("UDP timeout: ", err)
			masterChan <- true
			break
		}
		/*
			fmt.Println("I'm getting into this for")
			select {
			case <-time.After(time.Second * 3):
				fmt.Println("Master dead")
				masterChan <- true
				break L
				/*
					default:
						_, _, err := connection.ReadFromUDP(buffer)
						if err != nil {
							fmt.Println("You messed up in detect_precense.")
							panic(err)
						}
			}(*/
	}
}
开发者ID:sanntidT19,项目名称:Sanntid2016,代码行数:28,代码来源:phoenix.go

示例9: sendDataPacket

// sendDataPacket sends the given data packet to the connected client
// and waits for the correct ACK, or times out
func sendDataPacket(s *Server, d *pkt.DataPacket, con *net.UDPConn) error {
	_, err := con.Write(d.Bytes())
	if err != nil {
		return err
	}

	// Now wait for the ACK...
	maxtimeout := time.After(AckTimeout)
	ackch := make(chan error)

	// Move it to its own function
	go func() {
		ack := make([]byte, 256)
		for {
			n, _, err := con.ReadFromUDP(ack)
			if err != nil {
				ackch <- err
				return
			}

			pack, err := pkt.ParsePacket(ack[:n])
			if err != nil {
				ackch <- err
				return
			}

			// Check packet type
			ackpack, ok := pack.(*pkt.AckPacket)
			if !ok {
				ackch <- pkt.ErrPacketType
				return
			}

			if ackpack.GetBlocknum() != d.BlockNum {
				s.Logger.Warning("got ack(%d) but expected ack(%d)\n", d.BlockNum, ackpack.GetBlocknum())
				continue
			}
			ackch <- nil
			return
		}
	}()

	// Loop and retransmit until ack or timeout
	retransmit := time.After(RetransmitTime)
	for {
		select {
		case <-maxtimeout:
			return ErrTimeout
		case <-retransmit:
			s.Logger.Warning("Retransmit")
			_, err := con.Write(d.Bytes())
			if err != nil {
				return err
			}
			retransmit = time.After(RetransmitTime)
		case err := <-ackch:
			return err
		}
	}
}
开发者ID:brianredbeard,项目名称:astralboot,代码行数:62,代码来源:readreq.go

示例10: AcceptUDP

func AcceptUDP(UDP_Listner *net.UDPConn) {
	for {
		var (
			buf      = make([]byte, 1024)
			PlayerID ID
		)

		_, addr, err := UDP_Listner.ReadFromUDP(buf[0:])

		if err != nil {
			log.Printf("AcceptUDP error:" + err.Error())
			continue
		}
		if buf[0] == ID_ResolveUDP {
			PlayerID = ID(buf[3]) | (ID(buf[4]) << 8) | (ID(buf[5])<<16 | ID(buf[6])<<24)
			for _, c := range MainServer.Clients {
				if PlayerID == c.ID { // TODO: must be reply TCP message with approve connection
					log.Printf("%s pid=%d", addr.String(), PlayerID)
					c.UDPCon = UDP_Listner
					c.UDPAddr = addr
				}
			}
			buf = make([]byte, 1024)
			continue
		}
	}
}
开发者ID:magicafe,项目名称:Sket,代码行数:27,代码来源:Server.go

示例11: main

func main() {
	listen := flag.String("addr", ":2055", "Listen address")
	flag.Parse()

	var addr *net.UDPAddr
	var err error
	if addr, err = net.ResolveUDPAddr("udp", *listen); err != nil {
		log.Fatal(err)
	}

	var server *net.UDPConn
	if server, err = net.ListenUDP("udp", addr); err != nil {
		log.Fatal(err)
	}

	decoders := make(map[string]*netflow.Decoder)
	for {
		buf := make([]byte, 8192)
		var remote *net.UDPAddr
		if _, remote, err = server.ReadFromUDP(buf); err != nil {
			log.Printf("error reading from %s: %v\n", remote, err)
			continue
		}

		log.Printf("received %d bytes from %s\n", len(buf), remote)

		d, found := decoders[remote.String()]
		if !found {
			s := session.New()
			d = netflow.NewDecoder(s)
			decoders[remote.String()] = d
		}

		m, err := d.Read(bytes.NewBuffer(buf))
		if err != nil {
			log.Println("decoder error:", err)
			continue
		}

		switch p := m.(type) {
		case *netflow1.Packet:
			netflow1.Dump(p)

		case *netflow5.Packet:
			netflow5.Dump(p)

		case *netflow6.Packet:
			netflow6.Dump(p)

		case *netflow7.Packet:
			netflow7.Dump(p)

		case *netflow9.Packet:
			netflow9.Dump(p)

		case *ipfix.Message:
			ipfix.Dump(p)
		}
	}
}
开发者ID:nyxtom,项目名称:netflow,代码行数:60,代码来源:main.go

示例12: listenOutage

func listenOutage(conn *net.UDPConn) {
	for {
		b := make([]byte, 256)
		_, _, err := conn.ReadFromUDP(b)
		fmt.Println("read", string(b))
		t, m, err := message.DecodeClientToClientMessage(b)
		if err != nil {
			log.Println("[Client] Can't decode message", string(b))
		}
		switch t {
		case message.VOTE_T:
			// Start voting
			if !inVotingProcess {
				startVotingAlgorithm()
			}
			address := m.VoteMessage.Number
			fmt.Println("Got this address", address)
			if address != myAddress {
				// Add Adress to list of known address
				otherClientsAddress[address] = true
				fmt.Println("Known address", otherClientsAddress)
			}
		case message.COORDINATOR_T:
			Newaddr := m.CoordinatorMessage.Address
			fmt.Println("Coordinator", Newaddr)
			stopVotingProcess()
		}
		log.Println("[Client] Got", m)
	}
}
开发者ID:Madrigal,项目名称:GoUDP,代码行数:30,代码来源:GoUDP.go

示例13: serve

func (s *Server) serve(conn *net.UDPConn) {
	defer s.wg.Done()

	// From https://collectd.org/wiki/index.php/Binary_protocol
	//   1024 bytes (payload only, not including UDP / IP headers)
	//   In versions 4.0 through 4.7, the receive buffer has a fixed size
	//   of 1024 bytes. When longer packets are received, the trailing data
	//   is simply ignored. Since version 4.8, the buffer size can be
	//   configured. Version 5.0 will increase the default buffer size to
	//   1452 bytes (the maximum payload size when using UDP/IPv6 over
	//   Ethernet).
	buffer := make([]byte, 1452)

	for {
		n, _, err := conn.ReadFromUDP(buffer)
		if err != nil && s.conn != nil {
			log.Printf("Collectd ReadFromUDP error: %s", err)
			continue
		}
		log.Printf("received %d bytes", n)
		if n > 0 {
			s.handleMessage(buffer[:n])
		}
		if s.conn == nil {
			// we closed the connection, time to go
			return
		}
	}
}
开发者ID:pcn,项目名称:influxdb,代码行数:29,代码来源:collectd.go

示例14: udphandler

func (s *serv) udphandler(conn *net.UDPConn) {
	u := newUpstream(s.proto)
	u.udpconn = conn

	// add to pool
	s.pool.append(u, 0)
	defer func() {
		u.close()
		s.pool.remove(u)
	}()

	for {
		udpbuf := make([]byte, buffersize)
		n, addr, err := conn.ReadFromUDP(udpbuf)
		if err != nil {
			logrus.WithError(err).Warnln("ReadFromUDP error")
			break
		}
		if u.udpaddr == nil {
			u.udpaddr = addr
		}

		p := packet{}
		if err := decodePacket(udpbuf[:n], &p); err != nil {
			logrus.WithError(err).Warnln("server gop decode from udp error", n)
			continue
		}

		p.udp = true
		if err := s.proc(u, &p); err != nil {
			logrus.WithError(err).Warn("serve send pong err")
			return
		}
	}
}
开发者ID:tomasen,项目名称:trafcacc,代码行数:35,代码来源:server.go

示例15: getReplies

func (c *client) getReplies(so *net.UDPConn) {
	for {
		log.Println("here")
		b := make([]byte, 128)
		i, sa, err := so.ReadFromUDP(b)
		if err != nil {
			log.Println("failed to read from socket, ", err.Error())
			continue
		}

		tns := uint64(time.Now().UnixNano())
		macLen := 256 / 8
		mac := b[:macLen]
		message := b[macLen:i]

		if len(mac) != macLen || !checkMAC(message, mac, []byte(c.key)) {
			//Should count bad hmacs
			continue
		}

		rep := pb.PingReply{}
		proto.Unmarshal(message, &rep)
		go c.processReply(&rep, tns, sa)
	}
}
开发者ID:tcolgate,项目名称:radia,代码行数:25,代码来源:client.go


注:本文中的net.UDPConn.ReadFromUDP方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。