You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.1 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "net"
  5. "time"
  6. "github.com/fatih/color"
  7. )
  8. type PeersList struct {
  9. PeerID string
  10. Peers []Peer `json:"peerslist"`
  11. Date time.Time `json:"date"`
  12. }
  13. //var peersList []Peer
  14. var peersList PeersList
  15. func peerIsInPeersList(p Peer, pl []Peer) int {
  16. r := -1
  17. for i, peer := range pl {
  18. if peer.IP+":"+peer.Port == p.IP+":"+p.Port {
  19. r = i
  20. }
  21. }
  22. return r
  23. }
  24. func updatePeersList(conn net.Conn, newPeersList PeersList) {
  25. for _, peer := range newPeersList.Peers {
  26. if getIPPortFromConn(conn) == peer.IP+":"+peer.Port {
  27. peer.ID = newPeersList.PeerID
  28. color.Yellow(peer.ID)
  29. }
  30. i := peerIsInPeersList(peer, peersList.Peers)
  31. if i == -1 {
  32. peersList.Peers = append(peersList.Peers, peer)
  33. } else {
  34. fmt.Println(peersList.Peers[i])
  35. peersList.Peers[i].ID = peer.ID
  36. }
  37. }
  38. }
  39. func searchPeerAndUpdate(p Peer) {
  40. for _, peer := range peersList.Peers {
  41. color.Red(p.IP + ":" + p.Port)
  42. color.Yellow(peer.IP + ":" + peer.Port)
  43. if p.IP+":"+p.Port == peer.IP+":"+peer.Port {
  44. peer.ID = p.ID
  45. }
  46. }
  47. }
  48. //send the peersList to all the peers except the peer that has send the peersList
  49. func propagatePeersList(p Peer) {
  50. for _, peer := range peersList.Peers {
  51. if peer.Conn != nil {
  52. if peer.ID != p.ID && p.ID != "" {
  53. color.Yellow(peer.ID + " - " + p.ID)
  54. var msg Msg
  55. msg = msg.construct("PeersList", "here my peersList", peersList)
  56. msgB := msg.toBytes()
  57. _, err := peer.Conn.Write(msgB)
  58. check(err)
  59. } else {
  60. //to the peer that has sent the peerList, we send our ID
  61. /*
  62. var msg Msg
  63. var pl PeersList
  64. msg = msg.construct("MyID", runningPeer.ID, pl)
  65. msgB := msg.toBytes()
  66. _, err := p.Conn.Write(msgB)
  67. check(err)
  68. */
  69. var msg Msg
  70. msg = msg.construct("PeersList_Response", "here my peersList", peersList)
  71. msgB := msg.toBytes()
  72. _, err := peer.Conn.Write(msgB)
  73. check(err)
  74. }
  75. }
  76. }
  77. }
  78. func printPeersList() {
  79. fmt.Println("")
  80. color.Green("PEERSLIST:")
  81. color.Green("runningPeer.ID: " + runningPeer.ID)
  82. for _, peer := range peersList.Peers {
  83. fmt.Println(peer)
  84. }
  85. fmt.Println("")
  86. }