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.

67 lines
1.2 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"`
  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. func main() {
  21. //initialize some vars
  22. rand.Seed(time.Now().Unix())
  23. running = true
  24. var peer Peer
  25. color.Blue("Starting Peer")
  26. readConfig("config.json")
  27. peer.ID = strconv.Itoa(randInt(1, 1000)) //0 is reserved for server
  28. peer.IP = config.IP
  29. peer.Port = config.Port
  30. peer.Role = "client"
  31. //read flags, to know if is runned as p2p server
  32. if len(os.Args) > 1 {
  33. if os.Args[1] == "server" {
  34. color.Yellow("Running as p2p server")
  35. peer.Role = "server"
  36. peer.Port = config.ServerPort
  37. peer.ID = "0"
  38. }
  39. }
  40. thisPeerID = peer.ID
  41. peersList.PeerID = peer.ID
  42. fmt.Println(peer)
  43. peersList.Peers = append(peersList.Peers, peer)
  44. fmt.Println(peersList)
  45. if peer.Role == "server" {
  46. go acceptPeers(peer)
  47. }
  48. if peer.Role == "client" {
  49. var newPeer Peer
  50. newPeer.IP = config.ServerIP
  51. newPeer.Port = config.ServerPort
  52. newPeer.Role = "server"
  53. connectToPeer(newPeer)
  54. }
  55. for running {
  56. time.Sleep(1000 * time.Millisecond)
  57. }
  58. }