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


Golang net.UDPConn类代码示例

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


在下文中一共展示了UDPConn类的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: HandleVOIPData

func (tunnel *Tunnel) HandleVOIPData(buff []byte, addr *net.UDPAddr, conn *net.UDPConn) {
	now := time.Now().Unix()

	_, receiver, _, err := tunnel.ReadVOIPData(buff)
	if err != nil {
		return
	}

	client := tunnel.FindClient(addr)
	if client == nil || client.appid == 0 {
		return
	}

	client.timestamp = now
	//转发消息
	other := tunnel.FindAppClient(client.appid, receiver)
	if other == nil {
		log.Infof("can't dispatch voip data sender:%d receiver:%d", client.uid, receiver)
		return
	}

	if other.has_header {
		buffer := new(bytes.Buffer)
		var h byte = VOIP_DATA
		buffer.WriteByte(h)
		buffer.Write(buff)
		data := buffer.Bytes()
		conn.WriteTo(data, other.addr)
	} else {
		data := buff
		conn.WriteTo(data, other.addr)
	}
}
开发者ID:931743010,项目名称:voip_service,代码行数:33,代码来源:tunnel.go

示例3: udpKeepAlive

// udpKeepAlive sends a udp packet to keep the udp connection open
// This is still a bit of a "proof of concept"
func (v *VoiceConnection) udpKeepAlive(udpConn *net.UDPConn, close <-chan struct{}, i time.Duration) {

	if udpConn == nil || close == nil {
		return
	}

	var err error
	var sequence uint64

	packet := make([]byte, 8)

	ticker := time.NewTicker(i)
	for {

		binary.LittleEndian.PutUint64(packet, sequence)
		sequence++

		_, err = udpConn.Write(packet)
		if err != nil {
			v.log(LogError, "write error, %s", err)
			return
		}

		select {
		case <-ticker.C:
			// continue loop and send keepalive
		case <-close:
			return
		}
	}
}
开发者ID:42wim,项目名称:matterbridge,代码行数:33,代码来源:voice.go

示例4: PutRecv

func PutRecv(conn *net.UDPConn, context *UdpContext) int {
	file := context.file
	buffer := make([]byte, 1024)
	read, err := conn.Read(buffer)

	if err == io.EOF {
		break
	}

	if err != nil {
		fmt.Printf("Error reading from network: %s. Aborting transfer\n", err)
		return
	}

	_, err = file.Write(buffer[:read])
	if err != nil {
		fmt.Println("Error writing to file; aborting transfer")
		return
	}

	_, err = conn.Write([]byte("put-ack"))
	if err != nil {
		fmt.Println("Error writing ack; aborting transfer")
		return
	}

	return read
}
开发者ID:parthp022,项目名称:GoFtpServer,代码行数:28,代码来源:server.go

示例5: 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

示例6: fushCache

//发出缓存
func fushCache(conn *net.UDPConn, sendAddr *net.UDPAddr) {
	cacheArray := TempChanMap[sendAddr.IP.String()]

	/*    for item := cacheArray.Front();item != nil ; item = item.Next() {
	                fmt.Print("-");
			conn.WriteToUDP(item.Value.([]byte), sendAddr)
	    }
	*/
	length := TempChanMapIndex[sendAddr.IP.String()]
	fmt.Println(length, sendAddr.IP.String())
	for i := 0; i < length; i++ {
		if len(cacheArray[i]) > 0 {
			fmt.Print("-")
			position, err := conn.WriteToUDP(cacheArray[i], sendAddr)

			checkError(err)
			if err != nil {
				fmt.Println(position)
			}
		}
	}
	/*
	   for item := cacheArray.Front();item != nil ; item = item.Next() {
	      cacheArray.Remove(item)
	      fmt.Println("remove");
	   }
	*/
	TempChanMap[sendAddr.IP.String()] = make([][]byte, 1000, 1000000)
	TempChanMapIndex[sendAddr.IP.String()] = 0
	//fmt.Println(TempChanMap,sendAddr.IP.String());

}
开发者ID:hfeeki,项目名称:webrtcServer,代码行数:33,代码来源:udp_server.go

示例7: ListenForDsPackets

// Loops indefinitely to read packets and update connection status.
func ListenForDsPackets(listener *net.UDPConn) {
	var data [50]byte
	for {
		listener.Read(data[:])
		dsStatus := decodeStatusPacket(data)

		// Update the status and last packet times for this alliance/team in the global struct.
		dsConn := mainArena.AllianceStations[dsStatus.AllianceStation].DsConn
		if dsConn != nil && dsConn.TeamId == dsStatus.TeamId {
			dsConn.DriverStationStatus = dsStatus
			dsConn.LastPacketTime = time.Now()
			if dsStatus.RobotLinked {
				dsConn.LastRobotLinkedTime = time.Now()
			}
			dsConn.SecondsSinceLastRobotLink = time.Since(dsConn.LastRobotLinkedTime).Seconds()
			dsConn.DriverStationStatus.MissedPacketCount -= dsConn.missedPacketOffset

			// Log the packet if the match is in progress.
			matchTimeSec := mainArena.MatchTimeSec()
			if matchTimeSec > 0 && dsConn.log != nil {
				dsConn.log.LogDsStatus(matchTimeSec, dsStatus)
			}
		}
	}
}
开发者ID:fangeugene,项目名称:cheesy-arena,代码行数:26,代码来源:driver_station_connection.go

示例8: udpHandler

/**
  Handles a single UDP connection as a goroutine
*/
func udpHandler(buf []byte, b int, n int, conn *net.UDPConn, addr *net.UDPAddr) {
	defer fmt.Printf("Datagram %d sent!\n", n)

	// Slice buffer depending on read bytes, trim spaces
	clean := bytes.TrimSpace(buf[:b])

	// Decrypt incoming request []byte
	clean = decrypt(clean)

	// Parse the received JSON
	r := Request{}
	err := json.Unmarshal(clean, &r)
	if err != nil {
		fmt.Println(err)
		return
	}

	resp := findRoad(&r)

	// Convert to JSON, send over the wire
	s, err := json.Marshal(&resp)
	if err != nil {
		panic(err)
	}

	// Encrypt response []byte
	s = encrypt(s)

	conn.WriteToUDP(s, addr)
}
开发者ID:aksiksi,项目名称:roadomatic,代码行数:33,代码来源:server.go

示例9: serveUDP

// serveUDP starts a UDP listener for the server.
// Each request is handled in a separate goroutine.
func (srv *Server) serveUDP(l *net.UDPConn) error {
	defer l.Close()

	if srv.NotifyStartedFunc != nil {
		srv.NotifyStartedFunc()
	}

	reader := Reader(&defaultReader{srv})
	if srv.DecorateReader != nil {
		reader = srv.DecorateReader(reader)
	}

	handler := srv.Handler
	if handler == nil {
		handler = DefaultServeMux
	}
	rtimeout := srv.getReadTimeout()
	// deadline is not used here
	for {
		m, s, e := reader.ReadUDP(l, rtimeout)
		srv.lock.RLock()
		if !srv.started {
			srv.lock.RUnlock()
			return nil
		}
		srv.lock.RUnlock()
		if e != nil {
			continue
		}
		srv.inFlight.Add(1)
		go srv.serve(s.RemoteAddr(), handler, m, l, s, nil)
	}
}
开发者ID:thinkingo,项目名称:wagl,代码行数:35,代码来源:server.go

示例10: 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

示例11: Serve

// Serve starts the server using an existing UDPConn.
func (s *Server) Serve(conn *net.UDPConn) error {
	if s.rh == nil && s.wh == nil {
		return ErrNoRegisteredHandlers
	}

	s.connMu.Lock()
	s.conn = conn
	s.connMu.Unlock()

	s.connMu.RLock()
	defer s.connMu.RUnlock()
	buf := make([]byte, 65536) // Largest possible TFTP datagram
	for {
		numBytes, addr, err := conn.ReadFromUDP(buf)
		if err != nil {
			if s.close {
				return nil
			}
			return wrapError(err, "reading from conn")
		}

		// Make a copy of the received data
		b := make([]byte, numBytes)
		copy(b, buf)

		switch buf[1] {
		case 1: //RRQ
			go s.dispatchReadRequest(addr, b)
		case 2: //WRQ
			go s.dispatchWriteRequest(addr, b)
		default:
			go s.demuxToConn(addr, b)
		}
	}
}
开发者ID:u-root,项目名称:u-root,代码行数:36,代码来源:server.go

示例12: handlePacket

func (handler *VMessInboundHandler) handlePacket(conn *net.UDPConn, request *protocol.VMessRequest, packet v2net.Packet, clientAddr *net.UDPAddr) {
	ray := handler.vPoint.DispatchToOutbound(packet)
	close(ray.InboundInput())

	responseKey := md5.Sum(request.RequestKey)
	responseIV := md5.Sum(request.RequestIV)

	buffer := alloc.NewBuffer().Clear()
	defer buffer.Release()

	responseWriter, err := v2io.NewAesEncryptWriter(responseKey[:], responseIV[:], buffer)
	if err != nil {
		log.Error("VMessIn: Failed to create encrypt writer: %v", err)
		return
	}
	responseWriter.Write(request.ResponseHeader)

	hasData := false

	if data, ok := <-ray.InboundOutput(); ok {
		hasData = true
		responseWriter.Write(data.Value)
		data.Release()
	}

	if hasData {
		conn.WriteToUDP(buffer.Value, clientAddr)
		log.Info("VMessIn sending %d bytes to %s", buffer.Len(), clientAddr.String())
	}
}
开发者ID:vtroop,项目名称:v2ray-core,代码行数:30,代码来源:vmessin_udp.go

示例13: 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

示例14: udp_receive_server

func udp_receive_server(lconn, bconn *net.UDPConn, message_size int, receive_ch chan Udp_message) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("ERROR in udp_receive_server: %s \n Closing connection.", r)
			lconn.Close()
			bconn.Close()
		}
	}()

	bconn_rcv_ch := make(chan Udp_message)
	lconn_rcv_ch := make(chan Udp_message)

	go udp_connection_reader(lconn, message_size, lconn_rcv_ch)
	go udp_connection_reader(bconn, message_size, bconn_rcv_ch)

	for {
		select {

		case buf := <-bconn_rcv_ch:
			receive_ch <- buf

		case buf := <-lconn_rcv_ch:
			receive_ch <- buf
		}
	}
}
开发者ID:frimkus,项目名称:ttk4145-ex3,代码行数:26,代码来源:udp.go

示例15: ReadMessage

func ReadMessage(c *net.UDPConn) (msg *Message, src net.Addr, err os.Error) {
	buff := make([]byte, DHCP_MAX_LEN)
	//log.Printf("Waiting for read")
	n, src, err := c.ReadFromUDP(buff)
	if err != nil {
		return
	}
	if n < DHCP_MIN_LEN {
		err = os.NewError("Invalid DHCP messge received (too small)")
		return
	}
	buff = buff[0:n]
	msg = &Message{
		Operation:    buff[0],
		HardwareType: buff[1],
		HardwareLen:  buff[2],
		Hops:         buff[3],
		Xid:          binary.LittleEndian.Uint32(buff[4:8]),
		Secs:         binary.LittleEndian.Uint16(buff[8:10]),
		Flags:        binary.LittleEndian.Uint16(buff[10:12]),
		ClientIP:     net.IPv4(buff[12], buff[13], buff[14], buff[15]),
		YourIP:       net.IPv4(buff[16], buff[17], buff[18], buff[19]),
		ServerIP:     net.IPv4(buff[20], buff[21], buff[22], buff[23]),
		GatewayIP:    net.IPv4(buff[24], buff[25], buff[26], buff[27]),
	}
	copy(msg.ClientHWAddr[0:16], buff[28:44])
	// We skip the magic bytes and assume for now.
	msg.Options, err = ParseOptions(buff[DHCP_MIN_LEN+4:])
	//log.Printf("Parsed %d options.", len(msg.Options))
	// TODO: Handle Option 52 extensions.
	return
}
开发者ID:vonwenm,项目名称:GoDHCP,代码行数:32,代码来源:message.go


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