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.

73 lines
1.6 KiB

  1. package main
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "net"
  6. "os"
  7. "strconv"
  8. "time"
  9. "github.com/fatih/color"
  10. )
  11. type Peer struct {
  12. ID string `json:"id"` //in the future, this will be the peer hash
  13. IP string `json:"ip"`
  14. Port string `json:"port"`
  15. Role string `json:"role"` //client or server
  16. Conn net.Conn `json:"conn"`
  17. }
  18. var running bool
  19. var thisPeerID string
  20. var runningPeer Peer
  21. func main() {
  22. //initialize some vars
  23. rand.Seed(time.Now().Unix())
  24. running = true
  25. color.Blue("Starting Peer")
  26. //read configuration file
  27. readConfig("config.json")
  28. runningPeer.ID = strconv.Itoa(randInt(1, 1000)) //0 is reserved for server
  29. runningPeer.IP = config.IP
  30. runningPeer.Port = config.Port
  31. runningPeer.Role = "client"
  32. go runRestServer()
  33. //read flags, to know if is runned as p2p server
  34. if len(os.Args) > 1 {
  35. if os.Args[1] == "server" {
  36. color.Yellow("Running as p2p server")
  37. runningPeer.Role = "server"
  38. runningPeer.Port = config.ServerPort
  39. runningPeer.ID = "0"
  40. }
  41. }
  42. thisPeerID = runningPeer.ID
  43. outcomingPeersList.PeerID = runningPeer.ID
  44. fmt.Println(runningPeer)
  45. //outcomingPeersList.Peers = append(outcomingPeersList.Peers, runningPeer)
  46. outcomingPeersList = appendPeerIfNoExist(outcomingPeersList, runningPeer)
  47. fmt.Println(outcomingPeersList)
  48. if runningPeer.Role == "server" {
  49. go acceptPeers(runningPeer)
  50. }
  51. if runningPeer.Role == "client" {
  52. var newPeer Peer
  53. newPeer.ID = "0"
  54. newPeer.IP = config.ServerIP
  55. newPeer.Port = config.ServerPort
  56. newPeer.Role = "server"
  57. connectToPeer(newPeer)
  58. go acceptPeers(runningPeer)
  59. }
  60. for running {
  61. time.Sleep(1000 * time.Millisecond)
  62. }
  63. }