forked from cenkalti/rain
/
session_rpc_server.go
65 lines (54 loc) 路 1.25 KB
/
session_rpc_server.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
package torrent
import (
"context"
"expvar"
"net"
"net/http"
"net/rpc"
"strconv"
"time"
"github.com/kyoto44/rain/logger"
"github.com/powerman/rpc-codec/jsonrpc2"
)
type rpcServer struct {
rpcServer *rpc.Server
httpServer http.Server
log logger.Logger
}
func newRPCServer(ses *Session) *rpcServer {
h := &rpcHandler{session: ses}
srv := rpc.NewServer()
_ = srv.RegisterName("Session", h)
mux := http.NewServeMux()
mux.Handle("/debug/vars", expvar.Handler())
mux.HandleFunc("/move-torrent", h.handleMoveTorrent)
mux.Handle("/", jsonrpc2.HTTPHandler(srv))
return &rpcServer{
rpcServer: srv,
httpServer: http.Server{
Handler: mux,
},
log: logger.New("rpc server"),
}
}
func (s *rpcServer) Start(host string, port int) error {
addr := net.JoinHostPort(host, strconv.Itoa(port))
listener, err := net.Listen("tcp", addr)
if err != nil {
return err
}
s.log.Infoln("RPC server is listening on", listener.Addr().String())
go func() {
err := s.httpServer.Serve(listener)
if err == http.ErrServerClosed {
return
}
s.log.Fatal(err)
}()
return nil
}
func (s *rpcServer) Stop(timeout time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return s.httpServer.Shutdown(ctx)
}