-
-
Save iwanbk/2567033 to your computer and use it in GitHub Desktop.
A minimal python to go json-rpc implemention, sans HTTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import socket | |
s = socket.create_connection(("127.0.0.1", 5090)) | |
s.sendall(json.dumps(({"id": 1, "method": "Hello.Hello", "params": ["hello"]}))) | |
print s.recv(4096) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import socket | |
import itertools | |
class RPCClient(object): | |
def __init__(self, addr, codec=json): | |
self._socket = socket.create_connection(addr) | |
self._id_iter = itertools.count() | |
self._codec = codec | |
def _message(self, name, *params): | |
return dict(id=self._id_iter.next(), | |
params=list(params), | |
method=name) | |
def call(self, name, *params): | |
req = self._message(name, *params) | |
id = req.get('id') | |
mesg = self._codec.dumps(req) | |
self._socket.sendall(mesg) | |
# This will actually have to loop if resp is bigger | |
resp = self._socket.recv(4096) | |
resp = self._codec.loads(resp) | |
if resp.get('id') != id: | |
raise Exception("expected id=%s, received id=%s: %s" | |
%(id, resp.get('id'), resp.get('error'))) | |
if resp.get('error') is not None: | |
raise Exception(resp.get('error')) | |
return resp.get('result') | |
def close(self): | |
self._socket.close() | |
rpc = RPCClient(("127.0.0.1", 5090)) | |
for i in xrange(10000): | |
print rpc.call("Hello.Hello", "hello") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net" | |
"log" | |
"os" | |
"rpc" | |
"rpc/jsonrpc" | |
) | |
type Hello int | |
func (h *Hello) Hello(arg *string, reply *string) os.Error { | |
log.Println("received:", *arg) | |
*reply = "hello" | |
return nil | |
} | |
func main() { | |
l, err := net.Listen("tcp", "127.0.0.1:5090") | |
defer l.Close() | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Print("listening:", l.Addr()) | |
hello := new(Hello) | |
rpc.Register(hello) | |
for { | |
log.Print("waiting for connections...") | |
c, err := l.Accept() | |
if err != nil { | |
log.Printf("accept error: %s", c) | |
continue | |
} | |
log.Printf("connection started: %v", c.RemoteAddr()) | |
go jsonrpc.ServeConn(c) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment