diff --git a/p2p/client.go b/p2p/client.go index 0914a50..2a38cdb 100644 --- a/p2p/client.go +++ b/p2p/client.go @@ -25,7 +25,7 @@ type client struct { } func completeHandshake(conn net.Conn, r *bufio.Reader, infohash, peerID [20]byte) (*handshake.Handshake, error) { - conn.SetDeadline(time.Now().Local().Add(3 * time.Second)) + conn.SetDeadline(time.Now().Add(3 * time.Second)) defer conn.SetDeadline(time.Time{}) // Disable the deadline req := handshake.New(infohash, peerID) @@ -42,7 +42,7 @@ func completeHandshake(conn net.Conn, r *bufio.Reader, infohash, peerID [20]byte } func recvBitfield(conn net.Conn, r *bufio.Reader) (bitfield.Bitfield, error) { - conn.SetDeadline(time.Now().Local().Add(5 * time.Second)) + conn.SetDeadline(time.Now().Add(5 * time.Second)) defer conn.SetDeadline(time.Time{}) // Disable the deadline msg, err := message.Read(r) diff --git a/p2p/p2p.go b/p2p/p2p.go index b6bc394..14a41f1 100644 --- a/p2p/p2p.go +++ b/p2p/p2p.go @@ -7,6 +7,7 @@ import ( "log" "net" "runtime" + "time" "github.com/veggiedefender/torrent-client/message" ) @@ -105,6 +106,11 @@ func attemptDownloadPiece(c *client, pw *pieceWork) ([]byte, error) { buf: make([]byte, pw.length), } + // Setting a deadline helps get unresponsive peers unstuck. + // 30 seconds is more than enough time to download 16 Kb + c.conn.SetDeadline(time.Now().Add(30 * time.Second)) + defer c.conn.SetDeadline(time.Time{}) // Disable the deadline + for state.downloaded < pw.length { // Block and consume messages until not choked if c.choked { @@ -133,6 +139,7 @@ func attemptDownloadPiece(c *client, pw *pieceWork) ([]byte, error) { return nil, err } } + return state.buf, nil }