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


Golang UDPConn.Write方法代码示例

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


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

示例1: pingThread

func pingThread(pingConn *net.UDPConn) {
	p := []byte("1")
	for {
		_, _ = pingConn.Write(p)
		time.Sleep(time.Millisecond * 250)
	}
}
开发者ID:torees,项目名称:Sanntid,代码行数:7,代码来源:main.go

示例2: Handshake

// Handshake performs data exchange between DHT client and server
func (dht *DHTClient) Handshake(conn *net.UDPConn) error {
	// Handshake
	var req DHTMessage
	req.ID = "0"
	req.Query = PacketVersion
	req.Command = DhtCmdConn
	// TODO: rename Port to something more clear
	req.Arguments = fmt.Sprintf("%d", dht.P2PPort)
	req.Payload = dht.NetworkHash
	for _, ip := range dht.IPList {
		req.Arguments = req.Arguments + "|" + ip.String()
	}
	var b bytes.Buffer
	if err := bencode.Marshal(&b, req); err != nil {
		Log(Error, "Failed to Marshal bencode %v", err)
		conn.Close()
		return err
	}
	// TODO: Optimize types here
	msg := b.String()
	if dht.Shutdown {
		return nil
	}
	_, err := conn.Write([]byte(msg))
	if err != nil {
		Log(Error, "Failed to send packet: %v", err)
		conn.Close()
		return err
	}
	return nil
}
开发者ID:subutai-io,项目名称:p2p,代码行数:32,代码来源:dht.go

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

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

示例5: messageServer

func messageServer(c *net.UDPConn, message string) {
	log.Printf("Write to server: %q", message)
	n, err := c.Write([]byte(message))
	if n == 0 || err != nil {
		log.Fatalf("WriteToUDP failed: %v", err.Error())
	}
}
开发者ID:sourcehunter,项目名称:maexchen,代码行数:7,代码来源:mia-client.go

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

示例7: sendAck

func (c *TFTPServer) sendAck(conn *net.UDPConn, tid string) {
	pkt := &TFTPAckPkt{Opcode: OpcodeACK, Block: c.Connections[tid].block}
	conn.SetWriteDeadline(time.Now().Add(1 * time.Second))
	if _, err := conn.Write(pkt.Pack()); err != nil {
		log.Println(err)
	}
}
开发者ID:kwbales,项目名称:nitro-tftp,代码行数:7,代码来源:tftp_client_mgr.go

示例8: sendData

/* Send file data to TFTP server in DATA packets. */
func sendData(conn *net.UDPConn, filename string) {
	input, err := os.Open(filename)
	checkError(err)

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

		data := make([]byte, 516)
		copy(data, DATA)
		copy(data[4:], buf)
		_, err = conn.Write(data)
		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,代码来源:client.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: TickServer

//TickServer 将 c 传入的数据广播到局域网
func (server *UDPServer) TickServer(c <-chan []byte) (err error) {
	var conn *net.UDPConn
	fmt.Println("start TickServer")
	server.slock.Lock()
	for i := 0; i < 3; i++ {
		conn, err = net.DialUDP("udp", server.sendAddr, server.bcastAddr)
		if err == nil {
			break
		} else {
			fmt.Println("DialUDP err:", err)
		}
		time.Sleep(3 * time.Millisecond)
	}

	defer func() {
		if err := recover(); err != nil {
			fmt.Println("MY:", err)
		}
	}()
	stop := false
	p := &packet.NoticePacket{packet.STATE_OFFLINE, []byte(""), []byte("")}
	buf, _ := json.Marshal(p) //make the init packet
	tickchan := make(chan []byte, 128)
	go func(c chan []byte) { //tick function
		defer func() {
			conn.Close()
			server.slock.Unlock()
			fmt.Println("stop udp TickServer FINISH.")
		}()
		for {
			if stop {
				return
			}
			//fmt.Println("send: ", string(buf))
			_, err = conn.Write(buf)
			errorCheck(err)
			time.Sleep(time.Duration(server.tick) * time.Millisecond)
		}
	}(tickchan)
	for {
		timeout := make(chan bool)
		go func() {
			time.Sleep(5000 * time.Millisecond)
			timeout <- true
		}()
		select {
		case buf = <-c:
			//tickchan <- buf
		case <-timeout: //超时检测
		case <-server.sexitchan: //退出
			//server.slock.Lock()
			fmt.Println("stop udp TickServer....")
			stop = true
			return nil
		}
	}

	return nil
}
开发者ID:Banket004,项目名称:simplechat,代码行数:60,代码来源:server.go

示例11: sendUDP

func sendUDP(udpConn *net.UDPConn) {
	sendString := `Hello World!/usr/local/go/bin/go build -o /Users/jiaxun/IdeaProjects/socketTest/MacPing /Users/jiaxun/IdeaProjects/socketTest/main.go /Users/jiaxun/IdeaProjects/socketTest/MacPing`
	_, err := udpConn.Write([]byte(sendString))
	if err != nil {
		fmt.Println(err.Error())
		return
	}
}
开发者ID:jjjabc,项目名称:socketPing,代码行数:8,代码来源:main.go

示例12: myNetwork_clientSend

func myNetwork_clientSend(c *net.UDPConn, packet []byte) {
	if rand.Intn(4) != 10 { //25% failure rate
		c.Write(packet)
	} else {
		log.Println("Dropped Packet: ", packet)
	}

}
开发者ID:ibrahimolgacc,项目名称:customTCP,代码行数:8,代码来源:client.go

示例13: sendRiakMetrics

func sendRiakMetrics(conn *net.UDPConn, metrics *[]string) error {
	data := []byte(strings.Join(*metrics, "\n"))
	_, err := conn.Write(data)
	if err != nil {
		log.Println("Error sending metrics: %v", err)
	}
	return nil
}
开发者ID:jjmalina,项目名称:riak-statsd,代码行数:8,代码来源:main.go

示例14: sendOptAck

func (c *TFTPServer) sendOptAck(conn *net.UDPConn, tid string, opts map[string]string) {
	pkt := &tftp.TFTPOptionAckPkt{Opcode: tftp.OpcodeOptAck, Options: opts}
	conn.SetWriteDeadline(time.Now().Add(1 * time.Second))
	if _, err := conn.Write(pkt.Pack()); err != nil {
		log.Errorln(err)
	}
	c.Connections[tid].OptACKSent()
}
开发者ID:RobWC,项目名称:nitro-tftp,代码行数:8,代码来源:tftp_client_mgr.go

示例15: SendTest

func SendTest(i int, Conn *net.UDPConn) {
	msg := strconv.Itoa(i)
	buf := []byte(msg)
	_, err := Conn.Write(buf)
	if err != nil {
		fmt.Println(msg, err)
	}
}
开发者ID:cewillis001,项目名称:client,代码行数:8,代码来源:client.go


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