Ejemplo n.º 1
0
func pingThread(pingConn *net.UDPConn) {
	p := []byte("1")
	for {
		_, _ = pingConn.Write(p)
		time.Sleep(time.Millisecond * 250)
	}
}
Ejemplo n.º 2
0
// 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
}
Ejemplo n.º 3
0
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)
	}
}
Ejemplo n.º 4
0
// 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
		}
	}
}
Ejemplo n.º 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())
	}
}
Ejemplo n.º 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
}
Ejemplo n.º 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)
	}
}
Ejemplo n.º 8
0
/* 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
		}

	}
}
Ejemplo n.º 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
		}
	}
}
Ejemplo n.º 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
}
Ejemplo n.º 11
0
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
	}
}
Ejemplo n.º 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)
	}

}
Ejemplo n.º 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
}
Ejemplo n.º 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()
}
Ejemplo n.º 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)
	}
}
Ejemplo n.º 16
0
//发送心跳包
func SendOnlineMessage(udpConn *net.UDPConn) {
	for {
		//每间隔1s向服务器发送一次在线信息
		udpConn.Write([]byte(reflectString["在线"]))
		sleepTimer := time.NewTimer(time.Second)
		<-sleepTimer.C
	}
}
Ejemplo n.º 17
0
// 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)
	}
}
Ejemplo n.º 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())
		}
	}
}
Ejemplo n.º 19
0
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)
	}
}
Ejemplo n.º 20
0
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)

}
Ejemplo n.º 21
0
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))
	}
}
Ejemplo n.º 22
0
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"
}
Ejemplo n.º 23
0
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())
}
Ejemplo n.º 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())
}
Ejemplo n.º 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)
	}
}
Ejemplo n.º 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)
}
Ejemplo n.º 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()))
	}
}
Ejemplo n.º 28
0
/* 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
}
Ejemplo n.º 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
}
Ejemplo n.º 30
0
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)
	}
}