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.

79 lines
2.1 KiB

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "net"
  7. "github.com/fatih/color"
  8. )
  9. func acceptPeers(peer Peer) {
  10. fmt.Println("accepting peers at: " + peer.Port)
  11. l, err := net.Listen("tcp", peer.IP+":"+peer.Port)
  12. if err != nil {
  13. log.Println("Error accepting peers. Listening port: " + peer.Port)
  14. running = false
  15. }
  16. for running {
  17. conn, err := l.Accept()
  18. if err != nil {
  19. log.Println("Error accepting peers. Error accepting connection")
  20. running = false
  21. }
  22. var newPeer Peer
  23. newPeer.IP = getIPFromConn(conn)
  24. newPeer.Port = getPortFromConn(conn)
  25. newPeer.Conn = conn
  26. incomingPeersList = appendPeerIfNoExist(incomingPeersList, newPeer)
  27. go handleConn(conn, newPeer)
  28. }
  29. }
  30. func connectToPeer(peer Peer) {
  31. color.Green("connecting to new peer")
  32. log.Println("Connecting to new peer: " + peer.IP + ":" + peer.Port)
  33. conn, err := net.Dial("tcp", peer.IP+":"+peer.Port)
  34. if err != nil {
  35. log.Println("Error connecting to: " + peer.IP + ":" + peer.Port)
  36. return
  37. }
  38. peer.Conn = conn
  39. outcomingPeersList = appendPeerIfNoExist(outcomingPeersList, peer)
  40. go handleConn(conn, peer)
  41. }
  42. func handleConn(conn net.Conn, connPeer Peer) {
  43. connRunning := true
  44. log.Println("handling conn: " + conn.RemoteAddr().String())
  45. //reply to the conn, send the peerList
  46. var msg Msg
  47. msg.construct("PeersList", "here my outcomingPeersList")
  48. msg.PeersList = outcomingPeersList
  49. msgB := msg.toBytes()
  50. _, err := conn.Write(msgB)
  51. check(err)
  52. for connRunning {
  53. /*
  54. buffer := make([]byte, 1024)
  55. bytesRead, err := conn.Read(buffer)
  56. */
  57. newmsg, err := bufio.NewReader(conn).ReadString('\n')
  58. if err != nil {
  59. log.Println(err)
  60. connRunning = false
  61. } else {
  62. var msg Msg
  63. //msg = msg.createFromBytes([]byte(string(buffer[0:bytesRead])))
  64. msg = msg.createFromBytes([]byte(newmsg))
  65. messageHandler(connPeer, msg)
  66. }
  67. }
  68. //TODO add that if the peer closed is the p2p server, show a warning message at the peer
  69. log.Println("Peer: " + conn.RemoteAddr().String() + " connection closed")
  70. conn.Close()
  71. //TODO delete the peer from the outcomingPeersList --> DONE
  72. deletePeerFromPeersList(connPeer, &outcomingPeersList)
  73. color.Yellow("peer deleted, current peerList:")
  74. printPeersList()
  75. }