示例#1
0
文件: mbroker.go 项目: jahrain/gmb
func main() {
	bind_addr := flag.String("bind_ip", "127.0.0.1", "bind ip address")
	http_port := flag.Int("http_port", 9999, "listen http port")
	rpc_port := flag.Int("rpc_port", 9998, "listen rpc port")
	flag.Parse()

	go func() {
		addr, _ := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", *bind_addr, *rpc_port))
		listener, _ := net.ListenTCP("tcp", addr)
		rpcservice := new(RPCService)
		rpc.Register(rpcservice)
		rpc.HandleHTTP()
		for {
			conn, _ := listener.Accept()
			go rpc.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}()

	web.Get("/api/topics/([a-zA-Z0-9_\\-]+)/subscribers/([a-zA-Z0-9_\\-]+)/messages", APIGetTopicMessages)
	web.Post("/api/topics/([a-zA-Z0-9_\\-]+)/subscribers/([a-zA-Z0-9_\\-]+)/messages", APIPostTopicMessage)
	web.Get("/api/topics/([a-zA-Z0-9_\\-]+)", APIGetTopic)
	web.Post("/api/topics/([a-zA-Z0-9_\\-]+)", APIUpdateTopic)
	//web.Get("/api/topics", APIGetTopics)
	web.Get("/api/subscribers/([a-zA-Z0-9_\\-]+)", APIGetSubscriber)
	web.Post("/api/subscribers/([a-zA-Z0-9_\\-]+)", APIUpdateSubscriber)
	//web.Get("/api/topics/(.+)/subscribers/(.+)", APIGetTopicSubscriber)
	//web.Get("/api/topics/(.+)/subscribers", APIGetTopicSubscribers)

	web.Run(fmt.Sprintf("%s:%d", *bind_addr, *http_port))

}
示例#2
0
func TestWebSocket_Deliver(t *testing.T) {
	mux := http.NewServeMux()
	h := Handler{Tx: &smpp.Transceiver{Addr: ":0"}}
	<-h.Register(mux)
	s := httptest.NewServer(mux)
	defer s.Close()
	u := strings.Replace(s.URL, "http:", "ws:", 1)
	ws, err := websocket.Dial(u+"/v1/ws/jsonrpc/events", "", "http://localhost")
	if err != nil {
		t.Fatal(err)
	}
	defer ws.Close()
	h.pool.Broadcast(&DeliveryReceipt{
		Src:  "bart",
		Dst:  "lisa",
		Text: "delivery receipt here",
	})
	srv := rpc.NewServer()
	NewSM(h.Tx, srv)
	go func() {
		deliverErr <- srv.ServeRequest(jsonrpc.NewServerCodec(ws))
	}()
	select {
	case err = <-deliverErr:
		if err != nil {
			t.Fatal(err)
		}
	case <-time.After(2 * time.Second):
		t.Fatal("timeout waiting for delivery receipt")
	}
}
示例#3
0
func StartRpc() {
	if !g.Config().Rpc.Enabled {
		return
	}

	addr := g.Config().Rpc.Listen
	tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
	if err != nil {
		log.Fatalf("net.ResolveTCPAddr fail: %s", err)
	}

	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		log.Fatalf("listen %s fail: %s", addr, err)
	} else {
		log.Println("rpc listening", addr)
	}

	server := rpc.NewServer()
	server.Register(new(Transfer))

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Println("listener.Accept occur error:", err)
			continue
		}
		// go rpc.ServeConn(conn)
		go server.ServeCodec(jsonrpc.NewServerCodec(conn))
	}
}
示例#4
0
func InitJsonRpcServer(rcvr interface{}) {
	server := rpc.NewServer()
	server.Register(rcvr)

	listener, e := net.Listen("tcp", ":7498")
	if e != nil {
		log.Fatal("listen error:", e)
	}
	defer listener.Close()

	RpcHandler := func(w http.ResponseWriter, r *http.Request) {
		serverCodec := jsonrpc.NewServerCodec(&HttpConn{in: r.Body, out: w})
		w.Header().Set("Content-type", "application/json")
		w.WriteHeader(200)
		err := server.ServeRequest(serverCodec)
		if err != nil {
			log.Printf("Error while serving JSON request: %v", err)
			http.Error(w, "Error while serving JSON request, details have been logged.", 500)
			return
		}
	}

	r := mux.NewRouter()
	r.HandleFunc("/rpc", RpcHandler)
	go http.Serve(listener, r)
}
示例#5
0
func main() {
	var err error

	clientApp := exec.Command("./client-example", "")

	rwc := new(ReadWriteCloser)

	rwc.WriteCloser, err = clientApp.StdinPipe()
	if err != nil {
		log.Fatal(err)
	}

	rwc.ReadCloser, err = clientApp.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}

	serv := rpc.NewServer()
	codec := jsonrpc.NewServerCodec(rwc)
	fmt.Println("Made RPC server")
	m := new(Adder)
	serv.Register(m)
	fmt.Println("Registered adder service")

	err = clientApp.Start()
	if err != nil {
		log.Fatal(err)
	}

	go serv.ServeCodec(codec)

	clientApp.Wait()

	fmt.Printf("Adder has been called %d times and is now: %d\n", no, *m)
}
func main() {
	vtrade := new(VirtualTradingPlatform)
	vtrade.tradeid = 0
	server := rpc.NewServer()
	server.Register(vtrade)
	server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)

	listener, e := net.Listen("tcp", ":1234")

	if e != nil {
		fmt.Println("listen error:", e)
		return
	}

	fmt.Println("Server started")

	for {
		if conn, err := listener.Accept(); err != nil {
			fmt.Println("accept error: " + err.Error())
			log.Fatal("accept error: " + err.Error())
		} else {
			log.Printf("new connection established\n")
			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}
}
示例#7
0
func (d *daemon) startRPC() {
	if options.DebugPort > 0 {
		go func() {
			if err := http.ListenAndServe(fmt.Sprintf(":%d", options.DebugPort), nil); err != nil {
				glog.Errorf("Unable to bind to debug port %s. Is another instance running?", err)
				return
			}
		}()
	}

	listener, err := net.Listen("tcp", options.Listen)
	if err != nil {
		glog.Fatalf("Unable to bind to port %s. Is another instance running?")
	}

	rpcutils.SetDialTimeout(options.RPCDialTimeout)
	d.rpcServer.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)

	glog.V(0).Infof("Listening on %s", listener.Addr().String())
	go func() {
		for {
			conn, err := listener.Accept()
			if err != nil {
				glog.Fatalf("Error accepting connections: %s", err)
			}
			go d.rpcServer.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}()
}
示例#8
0
func (d *Daemon) serverloop() error {
	errorcount := 0
	for {
		if conn, err := d.l.Accept(); err != nil {
			errorcount++
			log4go.Error("Error accepting connection: %s", err)
			if errorcount > 10 {
				return log4go.Error("Too many errors, shutting server down")
			}
		} else {
			go func() {
				s := time.Now()
				conn.SetDeadline(time.Time{})
				codec := jsonrpc.NewServerCodec(conn)
				defer func() {
					codec.Close()
					if r := recover(); r != nil {
						log4go.Error("Recovered from panic: %v, stack: %s", r, string(debug.Stack()))
					}
					log4go.Debug("Serviced in %f milliseconds", time.Since(s).Seconds()*1000)
				}()
				for {
					if err := d.server.ServeRequest(codec); err != nil {
						log4go.Error("Error handling request: %v", err)
						break
					}
				}
			}()
		}
	}
}
示例#9
0
func StartServer(s *lb.Server) {
	go func() {
		serverStatus := &ServerStatus{s}

		server := rpc.NewServer()
		server.Register(serverStatus)

		address := fmt.Sprintf("%s:%d",
			s.Configuration.GeneralConfig.RPCHost,
			s.Configuration.GeneralConfig.RPCPort,
		)

		server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
		listener, e := net.Listen("tcp", address)
		if e != nil {
			log.Fatal("listen error:", e)
		}

		for {
			if conn, err := listener.Accept(); err != nil {
				log.Fatal("accept error: " + err.Error())
			} else {
				go server.ServeCodec(jsonrpc.NewServerCodec(conn))
			}
		}
	}()
}
示例#10
0
文件: main.go 项目: viney/go-json-rpc
func Run(clientName, clientUri string) (run func(), err error) {
	service := NewUserService()

	server := rpc.NewServer()
	if err := server.RegisterName(clientName, service); err != nil {
		return nil, err
	}

	run = func() {
		l, err := net.Listen("tcp", clientUri)
		if err != nil {
			log.Fatal("net.Listen: ", err)
		}
		defer l.Close()

		for {
			conn, err := l.Accept()
			if err != nil {
				log.Fatal("l.Accept: ", err)
			}
			defer conn.Close()

			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}

	return run, err
}
示例#11
0
// Create a new RPC server
func NewRpcServer(portNo uint16) (*rpc.Server, net.Listener) {
	server := rpc.NewServer()

	// Listens on a port
	l, e := net.Listen("tcp", fmt.Sprintf(":%d", portNo))
	if e != nil {
		log.Fatal("listen error:", e)
	}

	log.Infof("RPC Server is listening on %s\n", l.Addr())

	// run in background
	go func() {
		for {
			conn, err := l.Accept()
			if err != nil {
				// if listener closed, just exit the groutine
				if strings.Contains(err.Error(), "use of closed network connection") {
					return
				}
				log.Fatal(err)
			}

			log.Infof("Server accepted connection to %s from %s\n", conn.LocalAddr(), conn.RemoteAddr())

			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}()

	return server, l
}
示例#12
0
func startServerJSONRPC(port string) {
	log.Println("RPC on", port)

	srv := rpc.NewServer()
	s := new(MessageType)
	srv.Register(s)
	srv.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)

	// Listen function creates servers,
	// listening for incoming connections.
	ln, err := net.Listen("tcp", port)
	if err != nil {
		panic(err)
	}
	defer ln.Close()

	for {
		// Listen for an incoming connection.
		conn, err := ln.Accept()
		if err != nil {
			panic(err)
		}
		go srv.ServeCodec(jsonrpc.NewServerCodec(conn))
	}
}
示例#13
0
/// 启动rpcServer,监听rpc服务器端口,由于Start内部调用阻塞的方法,应在go 语句中调用.
func (ms *RpcServer) Start() {
	go func() {
		seelog.Info("RpcServer start...")
		hostAndPort := fmt.Sprintf("%v:%v", ms.host, ms.port)

		servAddr, err := net.ResolveTCPAddr("tcp", hostAndPort)

		if err != nil {
			seelog.Criticalf("RpcServer failed to start with err<%v>", err.Error())
			os.Exit(1)
		}

		listener, err := net.ListenTCP("tcp4", servAddr)

		if err != nil {
			seelog.Criticalf("RpcServer failed to start with err<%v>", err.Error())
			os.Exit(1)
		}

		seelog.Debugf("Rpc Server listening: <%v>", servAddr.String())
		defer listener.Close()

		for {
			conn, err := listener.Accept()

			seelog.Debug("Rpc Server accept new connection")
			if err != nil {
				seelog.Critical(err.Error())
				os.Exit(1)
			}
			go ms.rpcServer.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}()

}
示例#14
0
func (c *ProducerServer) StartRpc() error {
	log.Printf("Start to start rpc! \n")
	server := rpc.NewServer()
	err := c.RegistFunctions(server)
	if err != nil {
		log.Printf("consumer regist failed! \n")
		return err
	}
	server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
	log.Printf("Start to listen consumer rpc!%s \n", fmt.Sprintf("%s:%d", c.Address, c.RpcPort))
	l, e := net.Listen("tcp", fmt.Sprintf("%s:%d", c.Address, c.RpcPort))
	if e != nil {
		log.Printf("consumer listen failed err:%s! \n", e)
		return e
	}
	for {
		if c.IsShutDown {
			break
		}
		conn, err := l.Accept()
		if err != nil {
			log.Printf("accept err:%s \n", err)
			return err
		}
		go server.ServeCodec(jsonrpc.NewServerCodec(conn))
	}
	return nil
}
示例#15
0
func Start() {
	cfg := g.Config()
	if !cfg.Rpc.Enabled {
		log.Println("rpc.Start warning, not enable")
		return
	}
	addr := cfg.Rpc.Listen

	server := rpc.NewServer()
	server.Register(new(Agent))

	l, e := net.Listen("tcp", addr)
	if e != nil {
		log.Fatalln("rpc.Start error", e)
	} else {
		log.Println("rpc.Start ok, listening on", addr)
	}

	go func() {
		for {
			conn, err := l.Accept()
			if err != nil {
				if cfg.Debug {
					log.Println("rpc accept fail:", err)
				}
				time.Sleep(time.Duration(100) * time.Millisecond)
				continue
			}
			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}()
}
示例#16
0
func Start() {
	addr := g.Config().Listen

	server := rpc.NewServer()
	// server.Register(new(filter.Filter))
	server.Register(new(Agent))
	server.Register(new(Hbs))

	l, e := net.Listen("tcp", addr)
	if e != nil {
		log.Fatalln("listen error:", e)
	} else {
		log.Println("listening", addr)
	}

	for {
		conn, err := l.Accept()
		if err != nil {
			log.Println("listener accept fail:", err)
			time.Sleep(time.Duration(100) * time.Millisecond)
			continue
		}
		go server.ServeCodec(jsonrpc.NewServerCodec(conn))
	}
}
示例#17
0
// Run starts a debugger and exposes it with an HTTP server. The debugger
// itself can be stopped with the `detach` API. Run blocks until the HTTP
// server stops.
func (s *ServerImpl) Run() error {
	var err error
	// Create and start the debugger
	if s.s.debugger, err = debugger.New(&debugger.Config{
		ProcessArgs: s.s.config.ProcessArgs,
		AttachPid:   s.s.config.AttachPid,
	}); err != nil {
		return err
	}

	rpcs := grpc.NewServer()
	rpcs.Register(s.s)

	go func() {
		defer s.s.listener.Close()
		for {
			c, err := s.s.listener.Accept()
			if err != nil {
				select {
				case <-s.s.stopChan:
					// We were supposed to exit, do nothing and return
					return
				default:
					panic(err)
				}
			}
			go rpcs.ServeCodec(jsonrpc.NewServerCodec(c))
			if !s.s.config.AcceptMulti {
				break
			}
		}
	}()
	return nil
}
示例#18
0
func main() {
	list := new(Listener)
	buystock := new(Stock)
	list2 := new(Listenerx)

	server := rpc.NewServer()
	server.Register(list)
	server.Register(buystock)
	server.Register(list2)

	server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
	listener, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Fatal("listen error:", e)
	}
	for {
		if conn, err := listener.Accept(); err != nil {
			log.Fatal("accept error: " + err.Error())
		} else {
			log.Printf("new connection established\n")
			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}

	}

}
示例#19
0
func (s *SecureServer) Serve() error {
	if conn, err := s.conn.Accept(); err == nil {
		go s.rpcServ.ServeCodec(jsonrpc.NewServerCodec(conn))
	} else {
		return err
	}
	return nil
}
示例#20
0
func (s *ServerImpl) serveJSONCodec(conn io.ReadWriteCloser) {
	sending := new(sync.Mutex)
	codec := jsonrpc.NewServerCodec(conn)
	var req rpc.Request
	var resp rpc.Response
	for {
		req = rpc.Request{}
		err := codec.ReadRequestHeader(&req)
		if err != nil {
			if err != io.EOF {
				log.Println("rpc:", err)
			}
			break
		}

		mtype, ok := s.methodMaps[s.config.APIVersion-1][req.ServiceMethod]
		if !ok {
			log.Printf("rpc: can't find method %s", req.ServiceMethod)
			continue
		}

		var argv, replyv reflect.Value

		// Decode the argument value.
		argIsValue := false // if true, need to indirect before calling.
		if mtype.ArgType.Kind() == reflect.Ptr {
			argv = reflect.New(mtype.ArgType.Elem())
		} else {
			argv = reflect.New(mtype.ArgType)
			argIsValue = true
		}
		// argv guaranteed to be a pointer now.
		if err = codec.ReadRequestBody(argv.Interface()); err != nil {
			return
		}
		if argIsValue {
			argv = argv.Elem()
		}

		if mtype.Synchronous {
			replyv = reflect.New(mtype.ReplyType.Elem())
			function := mtype.method.Func
			returnValues := function.Call([]reflect.Value{mtype.Rcvr, argv, replyv})
			errInter := returnValues[0].Interface()
			errmsg := ""
			if errInter != nil {
				errmsg = errInter.(error).Error()
			}
			resp = rpc.Response{}
			s.sendResponse(sending, &req, &resp, replyv.Interface(), codec, errmsg)
		} else {
			function := mtype.method.Func
			ctl := &RPCCallback{s, sending, codec, req}
			go function.Call([]reflect.Value{mtype.Rcvr, argv, reflect.ValueOf(ctl)})
		}
	}
	codec.Close()
}
示例#21
0
文件: rdb.go 项目: donh/query
func (rpcTestEnvInstance *RpcTestEnv) ListenAndExecute(
	rcvr interface{}, rpcCallback func(*RpcTestEnv),
) {
	server := rpc.NewServer()
	server.Register(rcvr)

	var address = fmt.Sprintf("localhost:%d", rpcTestEnvInstance.Port)

	/**
	 * Listening RPC
	 */
	listener, err := net.Listen("tcp", address)
	if err != nil {
		panic(fmt.Errorf("Cannot listen TCP[%d]. Error: %v", rpcTestEnvInstance.Port, err))
	}

	log.Printf("Listen RPC at port [%d]", rpcTestEnvInstance.Port)
	// :~)

	go func() {
		for {
			conn, err := listener.Accept()

			if err != nil {
				if rpcTestEnvInstance.stop {
					log.Printf("Stop RPC server")
					rpcTestEnvInstance.wait <- true
				}

				break
			}

			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}()

	/**
	 * Initialize RPC client
	 */
	rpcTestEnvInstance.RpcClient, err = tknet.JsonRpcClient("tcp", address, time.Second*3)
	if err != nil {
		panic(fmt.Errorf("Initialize RPC client error: %v", err))
	}
	log.Printf("Construct RPC Client")
	// :~)

	defer func() {
		rpcTestEnvInstance.RpcClient.Close()
		rpcTestEnvInstance.stop = true
		listener.Close()
		<-rpcTestEnvInstance.wait
	}()

	rpcCallback(rpcTestEnvInstance)
}
示例#22
0
文件: receiver.go 项目: nsaje/dagger
// Listen starts receiving incoming records over RPC
func (r *receiver) Listen(errc chan error) {
	for {
		if conn, err := r.listener.Accept(); err != nil {
			log.Printf("[receiver] Accept error: " + err.Error())
			errc <- err
		} else {
			log.Printf("[receiver] New connection to the receiver established\n")
			go r.server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}
}
示例#23
0
func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	var conn, _, err = w.(http.Hijacker).Hijack()
	if err != nil {
		log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.Error())
		return
	}
	io.WriteString(conn, "HTTP/1.1 "+jsonRpcConnected+"\n")
	//io.WriteString(conn, "Access-Control-Allow-Origin: *\n")
	io.WriteString(conn, "Content-Type: application/json\n\n")
	server.ServeCodec(jsonrpc.NewServerCodec(conn))
}
示例#24
0
func runPipeServer(protoDebug bool) {
	protocol := new(protocol.Protocol)
	rpc.Register(protocol)
	pp, err := createPipePair(os.Stdin, os.Stdout, protoDebug)
	if err != nil {
		logger.Warning(fmt.Sprintf("Failed to create pipe pair: %s", err))
		return
	}
	codec := jsonrpc.NewServerCodec(pp)
	logger.Info("Starting...")
	rpc.ServeCodec(codec)
}
示例#25
0
文件: daemon.go 项目: WalterShe/wfdr
func monitorPipe(rwc io.ReadWriteCloser) {
	StartSharedSync()

	serv := rpc.NewServer()
	codec := jsonrpc.NewServerCodec(rwc)

	m := new(ModuleSrv)
	serv.Register(m)

	log.Println("RPC server is started and awaiting commands!")
	serv.ServeCodec(codec)
}
示例#26
0
func RPCServer(w http.ResponseWriter, req *http.Request) {
	h, buf, err := w.(http.Hijacker).Hijack()
	if err != nil {
		log.Print("ERR: ", err)
	}
	connected := "200 Connected to JSON-RPC"
	io.WriteString(h, "HTTP/1.0 "+connected+"\n\n")
	log.Print("Serving")
	codec := jsonrpc.NewServerCodec(combo{h, buf})
	rpc.ServeRequest(codec)
	h.Close()
}
示例#27
0
func (s *JSONRPCServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	log.Println("got a request")
	conn, _, err := w.(http.Hijacker).Hijack()
	if err != nil {
		log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.Error())
		return
	}
	io.WriteString(conn, "HTTP/1.0 200 Connected to Go JSON-RPC\n\n")
	codec := jsonrpc.NewServerCodec(conn)
	log.Println("ServeCodec")
	s.Server.ServeCodec(codec)
	log.Println("finished serving request")
}
示例#28
0
// NewJSONRPCHandler makes a JSON-RPC handler for s.
func NewJSONRPCHandler(s *rpc.Server) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer r.Body.Close()
		w.Header().Set("Content-Type", "application/json")
		var b bytes.Buffer
		var codec = jsonrpc.NewServerCodec(&readWriteCloser{r: r.Body, w: &b})
		if err := s.ServeRequest(codec); err != nil {
			panic(err)
		}
		codec.Close()
		io.Copy(w, &b)
	})
}
示例#29
0
//function for handling RPC connection
func handle(server *rpc.Server, conn net.Conn) {
	fmt.Println("start handle")
	//defer conn.Close() //make sure connection gets closed
	remote := conn.RemoteAddr().String() + " --> " + conn.LocalAddr().String()
	fmt.Println("==conn " + remote)
	//requests
	//doRequests(conn)
	// time.Sleep(3 * time.Second)

	fmt.Println("==conn " + remote)
	server.ServeCodec(jsonrpc.NewServerCodec(conn))
	fmt.Println("==discon " + remote)
	fmt.Println("end handle")
}
示例#30
0
文件: display.go 项目: uit-no/mrclean
func runService(display *Display) {
	rpc.Register(display)
	l, e := net.Listen("tcp", rpcserver)
	if e != nil {
		log.Fatal("listen error:", e)
	}
	for {
		conn, err := l.Accept()
		if err != nil {
			log.Fatal(err)
		}
		go rpc.DefaultServer.ServeCodec(jsonrpc.NewServerCodec(conn))
	}
}