2014-05-05 08:15:43 -05:00
|
|
|
package ethrpc
|
|
|
|
|
|
|
|
import (
|
2014-05-13 05:01:34 -05:00
|
|
|
"fmt"
|
2014-06-23 06:54:10 -05:00
|
|
|
"github.com/ethereum/eth-go/ethlog"
|
2014-06-26 12:45:57 -05:00
|
|
|
"github.com/ethereum/eth-go/ethpub"
|
2014-05-05 08:15:43 -05:00
|
|
|
"net"
|
|
|
|
"net/rpc"
|
|
|
|
"net/rpc/jsonrpc"
|
|
|
|
)
|
|
|
|
|
2014-06-23 06:54:10 -05:00
|
|
|
var logger = ethlog.NewLogger("JSON")
|
|
|
|
|
2014-05-05 08:15:43 -05:00
|
|
|
type JsonRpcServer struct {
|
|
|
|
quit chan bool
|
|
|
|
listener net.Listener
|
|
|
|
ethp *ethpub.PEthereum
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *JsonRpcServer) exitHandler() {
|
|
|
|
out:
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-s.quit:
|
|
|
|
s.listener.Close()
|
|
|
|
break out
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-06-23 06:54:10 -05:00
|
|
|
logger.Infoln("Shutdown JSON-RPC server")
|
2014-05-05 08:15:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *JsonRpcServer) Stop() {
|
|
|
|
close(s.quit)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *JsonRpcServer) Start() {
|
2014-06-23 06:54:10 -05:00
|
|
|
logger.Infoln("Starting JSON-RPC server")
|
2014-05-05 08:15:43 -05:00
|
|
|
go s.exitHandler()
|
|
|
|
rpc.Register(&EthereumApi{ethp: s.ethp})
|
|
|
|
rpc.HandleHTTP()
|
|
|
|
|
|
|
|
for {
|
|
|
|
conn, err := s.listener.Accept()
|
|
|
|
if err != nil {
|
2014-06-23 06:54:10 -05:00
|
|
|
logger.Infoln("Error starting JSON-RPC:", err)
|
2014-05-05 08:15:43 -05:00
|
|
|
break
|
|
|
|
}
|
2014-06-23 06:54:10 -05:00
|
|
|
logger.Debugln("Incoming request.")
|
2014-05-05 08:15:43 -05:00
|
|
|
go jsonrpc.ServeConn(conn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-05-13 05:01:34 -05:00
|
|
|
func NewJsonRpcServer(ethp *ethpub.PEthereum, port int) (*JsonRpcServer, error) {
|
|
|
|
sport := fmt.Sprintf(":%d", port)
|
|
|
|
l, err := net.Listen("tcp", sport)
|
2014-05-05 08:15:43 -05:00
|
|
|
if err != nil {
|
2014-05-13 04:49:55 -05:00
|
|
|
return nil, err
|
2014-05-05 08:15:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
return &JsonRpcServer{
|
|
|
|
listener: l,
|
|
|
|
quit: make(chan bool),
|
|
|
|
ethp: ethp,
|
2014-05-13 04:49:55 -05:00
|
|
|
}, nil
|
2014-05-05 08:15:43 -05:00
|
|
|
}
|