當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。