예제 #1
0
//	Asks computer from network where to connect to.
//	Returns address of the computer to which client should connect.
func (c *Client) Connect() (string, error) {
	log.Printf("Connecting client %s using %s\n", c.Address, c.KnownIp)

	//	Setup connection
	log.Printf("Creating socket to %s\n", c.KnownIp)
	conn, err := net.Dial("tcp", c.KnownIp+":666")
	if err != nil {
		return "", err
	}

	//	Create request
	log.Println("Creating message")
	request := sip.Message{}
	request.Type = "REQ"
	request.AddData("ip", c.Address)
	request.AddData("capacity", string(c.Capacity))

	//	Send request
	err = sip.Request(conn, request)

	//	Check if sending was successful
	if err != nil {
		return "", err
	}

	//	Get response
	log.Println("Waiting for response")
	var respBytes = make([]byte, 1024)
	n, err := conn.Read(respBytes)

	//	Check if there was error with read
	if err != nil {
		return "", err
	}

	//	Save response
	log.Println("Saving response")
	response := strings.Split(string(respBytes[:n]), protocols.GetSep())

	//	Get received data
	log.Printf("Getting data from response: %s\n", response)
	data := strings.Split(response[1], sip.GetDataSep())

	//	Find server address
	log.Printf("Looking for parent IP in data: %s\n", data)
	for _, s := range data {
		kv := strings.Split(s, "=")
		if kv[0] == "parent" {
			return kv[1], nil
		}
	}

	log.Println("No IP received")
	return "", nil
}
예제 #2
0
//	Sends chart through given socket
func SendChart(ip string) {
	socket, err := net.Dial("tcp", ip+":666")

	log.Println(err)

	sipMsg := sip.Message{}
	sipMsg.Type = "TRA"
	err = sip.Request(socket, sipMsg)

	if err != nil {
		log.Fatal(err)
	}

	chart, _ := os.OpenFile("./resources/chart.html", os.O_RDWR|os.O_APPEND, 0660)
	fileBytes := make([]byte, 2048)

	log.Println("Begginning transfer")

	for {
		n, _ := chart.Read(fileBytes)

		stpMsg := stp.Message{}
		stpMsg.Data = string(fileBytes[:n])

		err = stp.Request(socket, stpMsg)

		if err != nil {
			log.Fatal(err)
		}

		if n < 2048 {
			break
		}
	}

	log.Println("Transfer finished")

	socket.Write([]byte("END||"))
}