Example #1
0
func main() {
	math := new(Math)
	rpc.Register(math)

	tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
	if err != nil {
		fmt.Println("Fata error:", err)
		os.Exit(2)
	}

	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		fmt.Println("Fata error:", err)
		os.Exit(2)
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("conn error:", err)
			continue
		}
		jsonrpc.ServeConn(conn)
	}
}
// Main function
func main() {

	loadConfig()
	loadDict3()
	fingertable = make(map[int]NodeInfo)
	next = 0
	if entrypt == "null" {
		createChordRing()
	} else {
		joinChordRing(entrypt)
	}

	stabilize()
	check_predecessor()
	fixFingers()

	getDict3FromSuccessor()

	dic3 := new(DIC3)
	rpc.Register(dic3)

	tcpAddr, err := net.ResolveTCPAddr(protocol, port)
	checkError(err)
	fmt.Println("Server started........")
	listener, err := net.ListenTCP(protocol, tcpAddr)
	checkError(err)

	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		jsonrpc.ServeConn(conn)
	}
}
Example #3
0
// This example demonstrates a trivial echo server.
func main() {
	adder := &Adder{0}

	// Reset the counter every 30 seconds
	go func() {
		c := time.Tick(30 * time.Second)
		for _ = range c {
			adder.Reset()
		}
	}()

	// register our adder (adds the exposed methods)
	// set the http server to use /rpc as the websocket endpoint
	rpc.Register(adder)
	http.Handle("/rpc", websocket.Handler(func(ws *websocket.Conn) {
		jsonrpc.ServeConn(ws)
	}))

	// Serve static files
	http.Handle("/", http.FileServer(http.Dir(".")))
	err := http.ListenAndServe(":12345", nil)
	if err != nil {
		panic("ListenAndServe: " + err.Error())
	}
}
Example #4
0
func main() {
	fmt.Println("Starting Server...")

	winProc := new(Win32_Process)
	rpc.Register(winProc)

	winSvc := new(Win32_Service)
	rpc.Register(winSvc)

	//setup IP, port for the server
	tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
	checkError(err)

	//start to listen
	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)

	fmt.Println("Server Started")

	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		jsonrpc.ServeConn(conn)
	}
}
Example #5
0
func main() {
	// Create Babel service objects
	svc := new(gen.UserService)
	svc.SvcObj = NewUserServiceImpl()

	// Register the service with RPC
	rpc.Register(svc)

	// Register the service with Babel
	babel.Register(svc)

	// Set up Babel HTTP handlers and serve HTTP
	babel.HandleHTTP()
	http.Handle("/test/", http.StripPrefix("/test/", http.FileServer(http.Dir("../test"))))
	go func() { log.Fatal(http.ListenAndServe(":8333", nil)) }()

	//rpc.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)

	// set up network listener for json rpc
	l, e := net.Listen("tcp", ":8222")
	if e != nil {
		log.Fatal("listen error:", e)
	}

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

		go jsonrpc.ServeConn(conn)
	}
}
Example #6
0
func (s *Server) ServeHTTP(addr string, jsonRPCURL string, wsRPCURL string, useBasicAuth bool, userList map[string]string) {
	if s.rpcEnabled && jsonRPCURL != "" {
		s.httpEnabled = true
		Logger.Info("<HTTP> enabling handler for JSON-RPC")
		if useBasicAuth {
			http.HandleFunc(jsonRPCURL, use(handleRequest, basicAuth(userList)))
		} else {
			http.HandleFunc(jsonRPCURL, handleRequest)
		}
	}

	if s.rpcEnabled && wsRPCURL != "" {
		s.httpEnabled = true
		Logger.Info("<HTTP> enabling handler for WebSocket connections")
		wsHandler := websocket.Handler(func(ws *websocket.Conn) {
			jsonrpc.ServeConn(ws)
		})
		if useBasicAuth {
			http.HandleFunc(wsRPCURL, use(func(w http.ResponseWriter, r *http.Request) {
				wsHandler.ServeHTTP(w, r)
			}, basicAuth(userList)))
		} else {
			http.Handle(wsRPCURL, wsHandler)
		}
	}

	if !s.httpEnabled {
		return
	}
	if useBasicAuth {
		Logger.Info("<HTTP> enabling basic auth")
	}
	Logger.Info(fmt.Sprintf("<HTTP> start listening at <%s>", addr))
	http.ListenAndServe(addr, nil)
}
Example #7
0
func Start(conn *CGRConnector, user, pass string) {
	connector = conn
	username = user
	password = pass
	templates = template.Must(template.ParseGlob("templates/*.tmpl"))

	rpc.Register(conn)

	goji.Get(LOGIN_PATH, loginGet)
	goji.Post(LOGIN_PATH, loginPost)

	goji.Get("/app/*", http.FileServer(http.Dir("./static")))

	auth := web.New()
	goji.Handle("/*", auth)
	auth.Use(SessionAuth)
	auth.Handle("/ws", websocket.Handler(func(ws *websocket.Conn) {
		jsonrpc.ServeConn(ws)
	}))
	auth.Post("/import/", importPost)
	auth.Post("/exportcdrs/", exportCdrsPost)
	auth.Post("/exporttpcsv/", exportTpToCsvPost)
	auth.Get("/accounts/logout", logoutGet)
	auth.Get("/", http.RedirectHandler("/app/", 301))
}
Example #8
0
func (s *Server) ServeJSON(addr string) {
	if !s.rpcEnabled {
		return
	}
	lJSON, e := net.Listen("tcp", addr)
	if e != nil {
		log.Fatal("ServeJSON listen error:", e)
	}
	Logger.Info(fmt.Sprintf("Starting CGRateS JSON server at <%s>.", addr))
	errCnt := 0
	var lastErrorTime time.Time
	for {
		conn, err := lJSON.Accept()
		if err != nil {
			Logger.Err(fmt.Sprintf("<CGRServer> JSON accept error: <%s>", err.Error()))
			now := time.Now()
			if now.Sub(lastErrorTime) > time.Duration(5*time.Second) {
				errCnt = 0 // reset error count if last error was more than 5 seconds ago
			}
			lastErrorTime = time.Now()
			errCnt += 1
			if errCnt > 50 { // Too many errors in short interval, network buffer failure most probably
				break
			}
			continue
		}
		//utils.Logger.Info(fmt.Sprintf("<CGRServer> New incoming connection: %v", conn.RemoteAddr()))
		go jsonrpc.ServeConn(conn)
	}

}
Example #9
0
func Start() {
	// Start the server and accept connections on a
	// UNIX domain socket.
	rpc.Register(quartz)
	listener, err := net.Listen("unix", socketPath)
	if err != nil {
		panic(err)
	}
	for {
		conn, err := listener.Accept()
		if err != nil {
			panic(err)
		}
		go jsonrpc.ServeConn(conn)
	}

	// Destroy the socket file when the server is killed.
	sigc := make(chan os.Signal)
	signal.Notify(sigc, syscall.SIGTERM)
	go func() {
		<-sigc
		err := listener.Close()
		if err != nil {
			panic(err)
		}
		os.Exit(0)
	}()
}
Example #10
0
func (w *WebServer) start(host string) {
	http.HandleFunc("/ws-server",
		func(w http.ResponseWriter, req *http.Request) {
			s := websocket.Server{
				Handler: websocket.Handler(func(ws *websocket.Conn) {
					jsonrpc.ServeConn(ws)
				}),
			}
			s.ServeHTTP(w, req)
			log.Println("connected ws-server")
		})
	http.HandleFunc("/ws-client",
		func(rw http.ResponseWriter, req *http.Request) {
			s := websocket.Server{
				Handler: websocket.Handler(func(ws *websocket.Conn) {
					w.client = jsonrpc.NewClient(ws)
					w.ch <- struct{}{}
					<-w.ch
				}),
			}
			s.ServeHTTP(rw, req)
			log.Println("connected ws-client")
		})
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, r.URL.Path[1:])
	})
	if err := http.ListenAndServe(host, nil); err != nil {
		log.Fatal(err)
	}
}
func serverFun(serverInfo1 ServerConfig) {
	fmt.Println("Server Function started")
	//server start
	dictionaryFile = serverInfo1.PersistentStorageContainer

	dict3 := new(DICT3)
	rpc.Register(dict3)
	clientAddr, err := net.ResolveTCPAddr(serverInfo1.Protocol, ":"+strconv.Itoa(serverInfo1.MyPort))
	if err != nil {
		fmt.Println("Error1: ", err.Error)
		os.Exit(1)
	}
	listn, err := net.ListenTCP(serverInfo1.Protocol, clientAddr)
	if err != nil {
		fmt.Println("Error2: ", err.Error)
		os.Exit(1)
	}
	ReadFile(dictionaryFile) //load to map

	for {
		connect, err := listn.Accept()
		if err != nil {
			continue
		}
		go func() {
			jsonrpc.ServeConn(connect)
		}()
	}
}
Example #12
0
func main() {
	db, e := sql.Open("mysql", "root@/scan?charset=utf8")
	defer db.Close()
	if e != nil {
		fmt.Println("Не удалось подключится к БД: ", e)
	}

	bs := new(storage.BlockStorage)
	bs.DB = db
	is := new(storage.IpStorage)
	is.DB = db

	rpc.Register(bs)
	rpc.Register(is)

	tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
	checkError(err)

	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)

	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		go func(conn net.Conn) {
			jsonrpc.ServeConn(conn)
			//			conn.CloseWrite()
		}(conn)

	}
}
Example #13
0
func BenchmarkJSONRPC_pipe(b *testing.B) {
	cli, srv := net.Pipe()
	go jsonrpc.ServeConn(srv)
	client := jsonrpc.NewClient(cli)
	defer client.Close()
	benchmarkRPC(b, client)
}
Example #14
0
func main() {
	manager := new(TaskManager)
	rpc.Register(manager)

	tcpAddr, err := net.ResolveTCPAddr("tcp", ":8080")

	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}

		go jsonrpc.ServeConn(conn)

	}
}
Example #15
0
func main() {

	arith := new(Arith)
	rpc.Register(arith)

	tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
	checkError(err)

	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)

	/* This works:
	rpc.Accept(listener)
	*/
	/* and so does this:
	 */
	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		jsonrpc.ServeConn(conn)
	}

}
func (rpcServer *RPCServer) CreateServer() error {

	//register method
	rpcServer.logger.Println("In createserver")

	rpcServer.logger.Println(rpcServer.configObject.ServerID)
	if err := rpc.RegisterName(rpcServer.configObject.ServerID, new(RPCMethod)); err != nil {
		rpcServer.logger.Println(err)
		fmt.Println(err)
		return err

	}

	rpcServer.logger.Println(rpcServer.configObject.Protocol, ":"+strconv.Itoa(rpcServer.configObject.Port))
	tcpAddr, err := net.ResolveTCPAddr(rpcServer.configObject.Protocol, ":"+strconv.Itoa(rpcServer.configObject.Port))
	if err != nil {
		rpcServer.logger.Println(err)
		fmt.Println(err)
		return err
	}

	//listen on port
	listener, err := net.ListenTCP(rpcServer.configObject.Protocol, tcpAddr)
	if err != nil {
		rpcServer.logger.Println(err)
		fmt.Println(err)
		return err
	}

	//intialize db
	//var err error
	rpcServer.boltDB, err = bolt.Open(rpcServer.configObject.PersistentStorageContainer.PersistentFilePath, 0600, nil)
	if err != nil {
		fmt.Println(err)
		return err
	}

	//asynchronously start a methd and listen on channel
	go rpcServer.closeServerAndDB(listener)
	//infinite for to listen requests

	//asynchronously call Initialize Chord Node
	go rpcServer.InitializeChordNode()

	for {

		conn, err := listener.Accept()
		if err != nil {
			rpcServer.logger.Println(err)
			return err
		}

		go jsonrpc.ServeConn(conn)

	}

	return nil
}
Example #17
0
func JsonrpcHandler(ws *websocket.Conn) {
	//log.Println("connection websocket on jsonrpcHandler")
	key := readKey(ws)
	if !h.keyExists(key) {
		//log.Println("invalid key")
		return
	}
	jsonrpc.ServeConn(ws)
}
Example #18
0
func Fuzz(data []byte) int {
	c := &MyConn{data, false}
	jsonrpc.ServeConn(c)
	if !c.closed {
		panic("conn is not closed")
	}
	if runtime.Gosched(); runtime.NumGoroutine() > 100 {
		panic("goroutine leak")
	}
	return 0
}
Example #19
0
func TestRPC(t *testing.T) {
	tisOut := func() interface{} {
		return interface{}(&test.IntStr{})
	}

	// set up the server

	if err := rpc.Register(&test.CI{}); err != nil {
		t.Error(err.Error())
		return
	}

	for i := 0; i < 2; i++ {

		endPt := "localhost:808"
		endPt += string('8' + i)

		var up sync.WaitGroup
		up.Add(1)

		// start the protocol server
		go func(ii int, ep string) {
			listener, err := net.Listen("tcp", ep)
			if err != nil {
				t.Error(err.Error())
				return
			}
			up.Done()
			for {
				conn, err := listener.Accept()
				if err != nil {
					t.Error(err.Error())
					return
				}
				if ii == 0 {
					go rpc.ServeConn(conn)
				} else {
					go jsonrpc.ServeConn(conn)
				}
			}
		}(i, endPt)

		up.Wait()

		// run the client code
		var useJSON bool
		if i > 0 {
			useJSON = true
		}

		client(t, useJSON, tisOut, endPt)
		clientBad(t, useJSON, tisOut, endPt)
	}
}
// Entrance that builds and maintains the websocket connection for users
func BuildConnection(conn *websocket.Conn) {

	defer func() {
		if err := recover(); err != nil {
			log.Printf("********** WebSocket Error: %+v ***********\n", err)
			debug.PrintStack()
		}
	}()

	orgIdHex := conn.Request().URL.Query().Get("o")
	if orgIdHex == "" {
		return
	}

	wsCookie := ""
	for _, cc := range conn.Request().Cookies() {
		if cc.Name == "qortex" {
			wsCookie = cc.Value
			break
		}
	}
	if wsCookie == "" {
		return
	}

	member, _ := getSessionMember(wsCookie)
	if member == nil {
		return
	}

	activeOrg, err := MyActiveOrg(orgIdHex)
	if err != nil {
		utils.PrintStackAndError(err)
		return
	}

	user, err := users.FindById(activeOrg.Organization.Database, member.Id)
	if err != nil {
		utils.PrintStackAndError(err)
		return
	}

	onlineUser := activeOrg.GetOrInitOnlineUser(user, conn)
	log.Printf("----> New websocket connection for: %s, %+v running totally",
		user.Email, len(onlineUser.WsConns))

	// Holding the connection
	jsonrpc.ServeConn(conn)

	// Cut current connection and clean up related resources
	onlineUser.KillWebsocket(conn)
}
Example #21
0
func (p *Lb) rpcStart() (err error) {

	var addr *net.TCPAddr
	if !p.Params.Rpc {
		return nil
	}
	lb := &LB{lb: p}
	rpc.Register(lb)

	addr, err = net.ResolveTCPAddr("tcp", p.Params.RpcAddr)
	if err != nil {
		glog.Fatalf(MODULE_NAME+"rpc.Start error, net.ResolveTCPAddr failed, %s", err)
	}

	p.rpcListener, err = net.ListenTCP("tcp", addr)
	if err != nil {
		glog.Fatalf(MODULE_NAME+"rpc.Start error, listen %s failed, %s",
			p.Params.RpcAddr, err)
	} else {
		glog.Infof(MODULE_NAME+"%s rpcStart ok, listening on %s", p.Params.Name, p.Params.RpcAddr)
	}

	go func() {
		var tempDelay time.Duration // how long to sleep on accept failure
		for {
			conn, err := p.rpcListener.Accept()
			if err != nil {
				if p.status == specs.APP_STATUS_EXIT {
					return
				}
				if tempDelay == 0 {
					tempDelay = 5 * time.Millisecond
				} else {
					tempDelay *= 2
				}
				if max := 1 * time.Second; tempDelay > max {
					tempDelay = max
				}
				time.Sleep(tempDelay)
				continue
			}
			tempDelay = 0
			go func() {
				e := p.rpcConnects.insert(conn)
				defer p.rpcConnects.remove(e)
				jsonrpc.ServeConn(conn)
			}()
		}
	}()
	return err
}
Example #22
0
func main() {

	flag.Parse()
	var (
		tlsConfig *tls.Config
		l         net.Listener
		err       error
	)

	if len(*certFile) > 0 && len(*keyFile) > 0 {
		tlsConfig = &tls.Config{
			InsecureSkipVerify: *skipVerify,
		}

		tlsConfig.Certificates = make([]tls.Certificate, 1)
		tlsConfig.Certificates[0], err = tls.LoadX509KeyPair(*certFile, *keyFile)

		if err != nil {
			log.Fatalf("Error loading certificate/keyfile: %s", err.Error())
		}

		l, err = tls.Listen("tcp", "127.0.0.1:"+strconv.Itoa(*port), tlsConfig)

	} else {
		l, err = net.Listen("tcp", "127.0.0.1:"+strconv.Itoa(*port))
	}

	defer l.Close()

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

	log.Print("listening:", l.Addr())

	jsql := new(JSQL)
	rpc.Register(jsql)

	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)
	}
}
Example #23
0
// Accept unix|tcp connections and serve json RPCs
func (s *RpcServer) Serve() error {
	defer s.Shutdown()

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

		if err != nil {
			return err
		}

		go jsonrpc.ServeConn(conn)
	}

	panic("not reached")
}
Example #24
0
// Listen - Starts listening for JSON-RPC.
func Listen(address string) (err error) {
	// Start a listener on `address`
	listener, err := net.Listen("tcp", address)
	if err != nil {
		return
	}
	defer listener.Close()

	// Listening for connections
	for {
		if conn, err := listener.Accept(); err == nil {
			go jsonrpc.ServeConn(conn)
		}
	}
}
Example #25
0
func (s *JsonRpcServer) Start() {
	log.Println("[JSON] Starting JSON-RPC server")
	RegisterPackagesRpcPackages()
	rpc.HandleHTTP()

	// Start serving
	for {
		conn, err := s.listener.Accept()
		if err != nil {
			log.Println(err)
			continue
		}
		go jsonrpc.ServeConn(conn)
	}
}
Example #26
0
func Connect(ws *websocket.Conn) {
	Sockets = append(Sockets, ws)

	SendCommand("Connection.Ready", time.Now())
	jsonrpc.ServeConn(ws)

	var newsockets []*websocket.Conn
	for _, s := range Sockets {
		if s == ws {
			continue
		}
		newsockets = append(newsockets, s)
	}
	Sockets = newsockets
}
Example #27
0
// start a rpc server
func (this *RpcServer) server() {
	rpc.Register(this)
	listener, e := net.Listen(RPC_TYPE, ":"+strconv.Itoa(this.port))
	if e != nil {
		log.Println(e)
		return
	}
	for {
		if conn, err := listener.Accept(); err != nil {
			log.Println(err)
		} else {
			log.Println("new connection")
			go jsonrpc.ServeConn(conn)
		}
	}
}
Example #28
0
func main() {
	arith := new(Arith)
	rpc.Register(arith)

	tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
	checkError(err)

	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)

	for {
		conn, err := listener.Accept()
		checkError(err)
		jsonrpc.ServeConn(conn)
	}
}
Example #29
0
func (s *JsonRpcServer) Start() {
	logger.Infoln("Starting JSON-RPC server")
	go s.exitHandler()
	rpc.Register(&EthereumApi{pipe: s.pipe})
	rpc.HandleHTTP()

	for {
		conn, err := s.listener.Accept()
		if err != nil {
			logger.Infoln("Error starting JSON-RPC:", err)
			break
		}
		logger.Debugln("Incoming request.")
		go jsonrpc.ServeConn(conn)
	}
}
Example #30
0
func main() {
	st := new(St)
	rpc.Register(st)
	tcpAddr, err := net.ResolveTCPAddr("tcp", "localhost:1337")
	checkError(err)
	listener, err := net.ListenTCP("tcp", tcpAddr)
	checkError(err)
	// rpc.Accept(listener)
	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}
		jsonrpc.ServeConn(conn)
	}

}