-
Notifications
You must be signed in to change notification settings - Fork 1
/
TCPServer.go
74 lines (59 loc) · 1.25 KB
/
TCPServer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package torrent
import (
"fmt"
"net"
)
type TCPServer struct {
IP string
port uint16
connChannel chan net.Conn
exit bool
torrent *Torrent
}
func NewTCPServer(IP string, port uint16, torrent *Torrent) *TCPServer {
return &TCPServer{
IP: IP,
port: port,
connChannel: make(chan net.Conn),
torrent: torrent,
}
}
func (tcpServer *TCPServer) stop() {
tcpServer.exit = true
}
func (tcpServer *TCPServer) start() error {
tcpServer.exit = false
addr := fmt.Sprintf("%s:%d", tcpServer.IP, tcpServer.port)
listener, err := net.Listen("tcp", addr)
if err != nil {
return err
}
go tcpServer.handleConnection()
go func() {
for !tcpServer.exit {
conn, err := listener.Accept()
if err != nil {
println("Error accept:", err.Error())
}
go func() {
tcpServer.connChannel <- conn
}()
}
}()
return nil
}
func (tcpServer *TCPServer) handleConnection() {
for !tcpServer.exit {
select {
case conn := <-tcpServer.connChannel:
peer := &Peer{}
peer.connection = conn
peer.torrent = tcpServer.torrent
peer.remoteChoked = true
peer.localChoked = true
peer.localInterested = false
peer.localInterested = false
tcpServer.torrent.acceptPeerChannel <- peer
}
}
}