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.

84 lines
2.1 KiB

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