예제 #1
0
파일: main.go 프로젝트: torees/Sanntid
func pingThread(pingConn *net.UDPConn) {
	p := []byte("1")
	for {
		_, _ = pingConn.Write(p)
		time.Sleep(time.Millisecond * 250)
	}
}
예제 #2
0
파일: dht.go 프로젝트: subutai-io/p2p
// 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
}
예제 #3
0
파일: tftpd.go 프로젝트: meitros/tftp-go
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)
	}
}
예제 #4
0
파일: voice.go 프로젝트: 42wim/matterbridge
// 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
		}
	}
}
예제 #5
0
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())
	}
}
예제 #6
0
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
}
예제 #7
0
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)
	}
}
예제 #8
0
파일: client.go 프로젝트: evanqi/TFTP
/* 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
		}

	}
}
예제 #9
0
// 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
		}
	}
}
예제 #10
0
//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
}
예제 #11
0
파일: main.go 프로젝트: jjjabc/socketPing
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
	}
}
예제 #12
0
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)
	}

}
예제 #13
0
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
}
예제 #14
0
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()
}
예제 #15
0
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)
	}
}
예제 #16
0
//发送心跳包
func SendOnlineMessage(udpConn *net.UDPConn) {
	for {
		//每间隔1s向服务器发送一次在线信息
		udpConn.Write([]byte(reflectString["在线"]))
		sleepTimer := time.NewTimer(time.Second)
		<-sleepTimer.C
	}
}
예제 #17
0
파일: dht.go 프로젝트: subutai-io/p2p
// HandlePing - Receives a Ping message from server and sends a response
func (dht *DHTClient) HandlePing(data DHTMessage, conn *net.UDPConn) {
	Log(Trace, "Ping message from DHT")
	dht.LastDHTPing = time.Now()
	msg := dht.Compose(DhtCmdPing, dht.ID, "", "")
	_, err := conn.Write([]byte(msg))
	if err != nil {
		Log(Error, "Failed to send 'ping' packet: %v", err)
	}
}
예제 #18
0
func UDPSend(conn *net.UDPConn, ch_transmit <-chan []byte) {
	for {
		msg := <-ch_transmit
		_, err := conn.Write(msg)
		if err != nil {
			log.Printf("UDP write error: %s", err.Error())
		}
	}
}
예제 #19
0
파일: listen.go 프로젝트: noekleby/TTK4145
func transmit(socket *net.UDPConn) {
	for {
		time.Sleep(2000 * time.Millisecond)

		message := "From server: Hello I got your mesage"
		socket.Write([]byte(message))
		fmt.Println("Sendte: " + message)
	}
}
예제 #20
0
파일: udp.go 프로젝트: JorgenW/kaffetrakter
func write_to_udp(socket *net.UDPConn) {
	fmt.Println("Sender started")
	time.Sleep(time.Millisecond * 1)
	var p string
	p = "Hei, server" + ("\x00")
	arr := []byte(p)
	socket.Write(arr)

}
예제 #21
0
파일: sworm.go 프로젝트: peterbourgon/sworm
func loggedWrite(socket *net.UDPConn, b []byte) {
	n, err := socket.Write(b)
	if err != nil {
		log.Printf("sworm peer: write: %s", err)
	}
	if n != len(b) {
		log.Printf("sworm peer: write: %d from %d", n, len(b))
	}
}
예제 #22
0
파일: client.go 프로젝트: superboum/udptest
func udpTest(Conn *net.UDPConn) bool {
	buf := make([]byte, 1024)

	Conn.SetReadDeadline(time.Now().Add(1 * time.Second))
	Conn.Write([]byte("TEST"))
	n, _, _ := Conn.ReadFromUDP(buf)
	Conn.Close()
	return string(buf[:n]) == "OK\n"
}
예제 #23
0
파일: main.go 프로젝트: jjjabc/socketPing
func di(udpConn *net.UDPConn, rAddr *net.UDPAddr, chap []byte, sn uint32, state State) (n int, err error) {
	sendBytesBuffer := bytes.NewBuffer([]byte{})
	binary.Write(sendBytesBuffer, binary.BigEndian, n)
	len, _ := sendBytesBuffer.Write(chap)
	if len != chapLen {
		return 0, errChapPasswordForm
	}
	len, _ = sendBytesBuffer.Write(state.Bytes())
	return udpConn.Write(sendBytesBuffer.Bytes())
}
예제 #24
0
func (clt *HopClient) toServer(u *net.UDPConn, flag byte, payload []byte, noise bool) {
	hp := new(HopPacket)
	hp.Flag = flag
	hp.Seq = clt.Seq()
	hp.setPayload(payload)
	if noise {
		hp.addNoise(mrand.Intn(MTU - 64 - len(payload)))
	}
	u.Write(hp.Pack())
}
예제 #25
0
// Broadcast message via UDP using Json
func UdpSender(parameter elevdriver.Button, con_udp *net.UDPConn) {
	message, err := json.Marshal(parameter)
	PrintError(err)

	for {
		time.Sleep(1000 * time.Millisecond)
		_, err2 := con_udp.Write(message)
		PrintError(err2)
	}
}
예제 #26
0
func sendErrorWithoutLogging(udp_conn *net.UDPConn, addr *net.UDPAddr, code byte, emsg string) {
	sendbuf := make([]byte, 5+len(emsg))
	sendbuf[0] = 0
	sendbuf[1] = 5 // 5 => opcode for ERROR
	sendbuf[2] = 0
	sendbuf[3] = code // error code
	copy(sendbuf[4:], emsg)
	sendbuf[len(sendbuf)-1] = 0 // 0-terminator
	udp_conn.Write(sendbuf)
}
예제 #27
0
//发送消息
func SendMessage(udpConn *net.UDPConn) {
	scaner := bufio.NewScanner(os.Stdin)

	for scaner.Scan() {
		if scaner.Text() == "exit" {
			return
		}
		udpConn.Write([]byte(scaner.Text()))
	}
}
예제 #28
0
파일: client.go 프로젝트: evanqi/TFTP
/* Run the initial protocol with the TFTP server. */
func initialProtocol(conn *net.UDPConn, opcode []byte, filename string) (n int, resp []byte) {
	resp = make([]byte, 516)
	req := constructRequest(opcode, filename)
	_, err := conn.Write(req)
	checkError(err)
	n, _, err = conn.ReadFromUDP(resp)
	checkError(err)

	return
}
예제 #29
0
func SendData(conn net.UDPConn, a string) int {
	data := make([]byte, 4096)
	data = []byte(a)

	n, err := conn.Write(data)
	if err != nil {
		fmt.Println("Error writing to connection: (UDP)", err.Error())
		return -1
	}
	return n
}
func WriteThing(conn *net.UDPConn) {
	for {
		data := []byte("Testing 123")
		sent_bytes, err := conn.Write(data)
		if err != nil {
			log.Fatal(err)
		}
		log.Println("Sent", sent_bytes, "bytes")
		time.Sleep(1 * time.Second)
	}
}