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


Golang UDPConn.WriteToUDP方法代码示例

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


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

示例1: handleUdpForwardLocal

func (s *UdpForwardServer) handleUdpForwardLocal(conn *net.UDPConn, laddr, raddr *net.UDPAddr, data []byte) {
	lconn, err := net.ListenUDP("udp", nil)
	if err != nil {
		glog.V(LWARNING).Infof("[udp] %s -> %s : %s", laddr, raddr, err)
		return
	}
	defer lconn.Close()

	if _, err := lconn.WriteToUDP(data, raddr); err != nil {
		glog.V(LWARNING).Infof("[udp] %s -> %s : %s", laddr, raddr, err)
		return
	}
	glog.V(LDEBUG).Infof("[udp] %s >>> %s length %d", laddr, raddr, len(data))

	b := make([]byte, MediumBufferSize)
	lconn.SetReadDeadline(time.Now().Add(ReadTimeout))
	n, addr, err := lconn.ReadFromUDP(b)
	if err != nil {
		glog.V(LWARNING).Infof("[udp] %s <- %s : %s", laddr, raddr, err)
		return
	}
	glog.V(LDEBUG).Infof("[udp] %s <<< %s length %d", laddr, addr, n)

	if _, err := conn.WriteToUDP(b[:n], laddr); err != nil {
		glog.V(LWARNING).Infof("[udp] %s <- %s : %s", laddr, raddr, err)
	}
	return
}
开发者ID:guest6379,项目名称:gost,代码行数:28,代码来源:forward.go

示例2: handleCall

func (s *UDPServer) handleCall(conn *net.UDPConn) {
	// Read and buffer UDP datagram
	b := make([]byte, MaxUdpSize)

	packetSize, callerAddr, err := conn.ReadFromUDP(b)
	if err != nil {
		s.server.log.WithField("err", err).Error("Cannot read UDP datagram")

		return
	}

	reply, err := s.server.handleRecord(b[0:packetSize])
	if err != nil {
		s.server.log.WithField("err", err).Error("handling record")
	}

	if _, err := conn.WriteToUDP(reply.Bytes(), callerAddr); err != nil {
		s.server.log.WithFields(logrus.Fields{
			"callerAddr": callerAddr.String(),
			"err":        err,
		}).Error("Cannot send reply over UDP")

		return
	}
}
开发者ID:develersrl,项目名称:go-sunrpc,代码行数:25,代码来源:udpserver.go

示例3: retrieveFortune

func retrieveFortune(clientConn net.UDPConn, fortuneInfoMsg clientServerUtils.FortuneInfoMessage) clientServerUtils.FortuneMessage {
	//Send FortuneReqMessage to fserver
	fortuneReqMsg := clientServerUtils.FortuneReqMessage{fortuneInfoMsg.FortuneNonce}
	fortuneReq, err := json.Marshal(fortuneReqMsg)
	if err != nil {
		fmt.Println("Error marshalling fortuneReqMsg: ", err)
		os.Exit(-1)
	}

	fmt.Println("Retrieving fortune from fserver")
	fserverUDPAddr := resolveUDPAddr(fortuneInfoMsg.FortuneServer)
	_, err = clientConn.WriteToUDP(fortuneReq, &fserverUDPAddr)
	if err != nil {
		fmt.Println("Error writing to fserver: ", err)
		os.Exit(-1)
	}

	//Receive FortuneMessage reply from fserver
	var buf [1024]byte
	msgLen, err := clientConn.Read(buf[:])
	if err != nil {
		fmt.Println("Error on read: ", err)
		os.Exit(-1)
	}
	fortuneReplyStr := string(buf[0:msgLen])
	fortuneBytes := []byte(fortuneReplyStr)

	var fortune clientServerUtils.FortuneMessage
	json.Unmarshal(fortuneBytes, &fortune)
	return fortune
}
开发者ID:msayson,项目名称:goSamples,代码行数:31,代码来源:client.go

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

示例5: udpHandler

func (s ServerUdp) udpHandler(conn *net.UDPConn) {
	var buf [512]byte
	_, addr, err := conn.ReadFromUDP(buf[0:])
	if err != nil {
		log.Printf("Error: %s \n", err)
	}
	var hash int = 0
	for _, d := range buf[11:] {
		hash += int(d)
	}
	gethash, _ := strconv.Atoi(string(buf[5:10]))

	if string(buf[0:5]) == "MAGIC" && hash == gethash {
		_, err = conn.WriteToUDP([]byte("200"), addr)
		if err != nil {
			log.Printf("Error: %s \n", err)
		}
	} else {
		_, err = conn.WriteToUDP([]byte("400"), addr)
		if err != nil {
			log.Printf("Error: %s \n", err)
		}
		log.Printf("Inv UDP %s From %v:%v,Ignored\n", string(buf[0:]), addr.IP, addr.Port)
		return
	}
	log.Printf("Recv GPRMC From %v:%v\n%s\n", addr.IP, addr.Port, string(buf[0:]))
	s.Info <- buf[11:len(buf)]
}
开发者ID:justsuperman,项目名称:project,代码行数:28,代码来源:udpserver.go

示例6: handleClient

func handleClient(conn *net.UDPConn, sb []byte) {
	var buf [256]byte
	size, addr, err := conn.ReadFromUDP(buf[0:])
	//println(size, addr)
	if err != nil {
		return
	}
	if size < 48 {
		return
	}
	sec, microsec := gettimeofday()
	vn := byteArrayToUint64(buf[0:][0:3]) & 0x38000000
	copy(sb[0:3], uint64ToByteArray(0x040106F0|vn)) // flag
	copy(sb[4:7], []byte{0, 0, 0, 0})               //delay
	copy(sb[8:11], uint64ToByteArray(0x00000010))   // dispersion
	copy(sb[12:15], []byte("LOCL"))                 // Ref ID
	copy(sb[16:19], uint64ToByteArray(sec+0x83AA7E80))
	copy(sb[20:23], []byte{0, 0, 0, 0})
	copy(sb[24:31], buf[0:][40:47])
	copy(sb[32:35], uint64ToByteArray(sec+0x83AA7E80))
	copy(sb[36:39], uint64ToByteArray((microsec/500000)*0x80000000))
	sec, microsec = gettimeofday()
	copy(sb[40:43], uint64ToByteArray(sec+0x83AA7E80))
	copy(sb[44:47], uint64ToByteArray((microsec/500000)*0x80000000))

	conn.WriteToUDP([]byte(sb), addr)
}
开发者ID:pekopeko1,项目名称:simple_ntp_server,代码行数:27,代码来源:ntp_base.go

示例7: sendAck

/* Constructs and sends an ACK packet over conn. */
func sendAck(conn *net.UDPConn, addr *net.UDPAddr) {
	ack := make([]byte, 4)
	copy(ack, ACK)
	//TODO copy block number
	_, err := conn.WriteToUDP(ack, addr)
	checkError(err)
}
开发者ID:evanqi,项目名称:TFTP,代码行数:8,代码来源:tftp.go

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

示例9: 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 := bytes.NewBuffer(make([]byte, 0, bufferSize))

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

	hasData := false

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

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

示例10: sendData

/* Sends file data in DATA packets over conn. */
func sendData(conn *net.UDPConn, addr *net.UDPAddr, filename string) {
	input, err := os.Open(filename)
	checkError(err)

	buf := make([]byte, 512)
	for {
		n, err := input.Read(buf)
		checkError(err)

		data := make([]byte, n+4)
		copy(data, DATA)
		copy(data[4:], buf[:n])
		_, err = conn.WriteToUDP(data, addr)
		checkError(err)

		if n < len(buf) {
			finalAck := make([]byte, 4)
			for !bytes.Equal(finalAck[0:2], ACK) {
				_, _, err := conn.ReadFromUDP(finalAck)
				checkError(err)
			}

			break
		}
	}

}
开发者ID:evanqi,项目名称:TFTP,代码行数:28,代码来源:tftp.go

示例11: parseAndAck

// parseAndAck parses the UDP payload and sends anwACK to the client receiver.
// TODO(jvesuna): Keep parseAndAck routine live with a connection. Have the ackServer channel data
// to this routine for faster processing.
func parseAndAck(buf []byte, ServerConn *net.UDPConn, clientUDPAddr *net.UDPAddr) {
	messageAck := &ptpb.PingtestMessage{}
	if err := proto.Unmarshal(buf, messageAck); err != nil {
		//TODO(jvesuna): Fix this error handling.
		log.Println("error: failed to unmarshal packet in parseAndAck:", err)
	}

	if *tinyAck {
		// Don't include padding.
		// Here, messageAck should always be about the same size.
		messageAck = &ptpb.PingtestMessage{
			PingtestParams: messageAck.PingtestParams,
			Type:           messageAck.Type,
		}
	}

	wireBytesAck, err := proto.Marshal(messageAck)
	if err != nil {
		fmt.Println("error marshalling ACK:", err)
	}

	// Send ACK.
	ServerConn.SetWriteBuffer(proto.Size(messageAck))
	_, err = ServerConn.WriteToUDP(wireBytesAck, clientUDPAddr)
	if err != nil {
		log.Println("Failed to send ACK:", err)
	}
	log.Println("Sent Ack")
}
开发者ID:JamshedVesuna,项目名称:pingtest,代码行数:32,代码来源:server.go

示例12: SendAChunk

func SendAChunk(conn *net.UDPConn, addr *net.UDPAddr, isServer bool) {
	var n2 int
	var err error
	var datablock []byte
	//Send the chink that we have in the Block (it is either the previous one being retransmitted or a the next one
	var opcode = "\x00\x03" //Data packet
	var blocknumBytes = make([]byte, 2)
	binary.BigEndian.PutUint16(blocknumBytes, uint16(chunk.blocknum))

	datablock = append(datablock, []byte(opcode)...)
	datablock = append(datablock, blocknumBytes...)
	fmt.Println("Stage 2: Datablock ", datablock)
	if chunk.nbytes < 512 {
		// make a slice of size chunk.nbytes and copy the data into it
		tempbuf := make([]byte, chunk.nbytes)
		n1 := copy(tempbuf, chunk.buf[0:chunk.nbytes])
		fmt.Println("Copied %d bytes to the last chunk being sent", n1)
		datablock = append(datablock, tempbuf...)
	} else {
		datablock = append(datablock, chunk.buf...)
	}
	fmt.Println("sending datablock", datablock)
	if isServer {
		n2, err = conn.WriteToUDP(datablock, addr)
	} else {
		n2, err = conn.Write(datablock)
	}
	fmt.Println("Number of Bytes sent is ", n2)
	if err != nil {
		fmt.Printf("Couldn't send datablock %v", err)
	}
}
开发者ID:meitros,项目名称:tftp-go,代码行数:32,代码来源:tftpd.go

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

示例14: udp_transmit_server

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

	var err error
	var n int

	for {
		//		fmt.Printf("udp_transmit_server: waiting on new value on Global_Send_ch \n")
		msg := <-send_ch
		//		fmt.Printf("Writing %s \n", msg.Data)
		if msg.Raddr == "broadcast" {
			n, err = lconn.WriteToUDP([]byte(msg.Data), baddr)
		} else {
			raddr, err := net.ResolveUDPAddr("udp", msg.Raddr)
			if err != nil {
				fmt.Printf("Error: udp_transmit_server: could not resolve raddr\n")
				panic(err)
			}
			n, err = lconn.WriteToUDP([]byte(msg.Data), raddr)
		}
		if err != nil || n < 0 {
			fmt.Printf("Error: udp_transmit_server: writing\n")
			panic(err)
		}
		//		fmt.Printf("udp_transmit_server: Sent %s to %s \n", msg.Data, msg.Raddr)
	}
}
开发者ID:frimkus,项目名称:ttk4145-ex3,代码行数:33,代码来源:udp.go

示例15: listenUdp

func listenUdp(c *net.UDPConn) {
	//m := make(map[string]int, 100)
	for {
		var message string

		buf := make([]byte, MAIN_BUFFER_SIZE)
		n, addr, err := c.ReadFromUDP(buf)

		if err != nil {
			log.Fatalln("error reading UDP: ", err)
			//break
		}
		message = string(buf[0:n])
		log.Println("received message from ", addr, message)

		writeSize, writeErr := c.WriteToUDP(buf, addr)
		if writeErr != nil {
			log.Fatalln("error writing UDP: ", writeErr, writeSize)
			//break
		}

		// IF this is a chat message, broadcast it:
		//h.broadcast <- message
		// TODO: IF this is a movement command, hand it to nav system
		// TODO: IF we don't recognize it, throw an error
	}
	c.Close()
}
开发者ID:DavidYKay,项目名称:blimpy,代码行数:28,代码来源:chatserver.go


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