当前位置: 首页>>代码示例>>Golang>>正文


Golang rpc.NewServer函数代码示例

本文整理汇总了Golang中net/rpc.NewServer函数的典型用法代码示例。如果您正苦于以下问题:Golang NewServer函数的具体用法?Golang NewServer怎么用?Golang NewServer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewServer函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: main

/////////////////////////////////
//MAIN
/////////////////////////////////
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
	var memprofile = flag.String("memprofile", "", "write memory profile to this file")
	var id *int = flag.Int("i", 0, "id [num]")
	var port1 *int = flag.Int("p1", 8000, "port1 [num]")
	var port2 *int = flag.Int("p2", 8001, "port2 [num]")
	var servers *string = flag.String("s", "", "servers [file]")
	var numClients *int = flag.Int("n", 0, "num clients [num]")
	var mode *string = flag.String("m", "", "mode [m for microblogging|f for file sharing]")
	flag.Parse()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	ss := ParseServerList(*servers)

	SetTotalClients(*numClients)

	s := NewServer(*port1, *port2, *id, ss, *mode == "f")

	if *memprofile != "" {
		f, err := os.Create(*memprofile)
		if err != nil {
			log.Fatal(err)
		}
		s.memProf = f
	}

	rpcServer1 := rpc.NewServer()
	rpcServer2 := rpc.NewServer()
	rpcServer1.Register(s)
	rpcServer2.Register(s)
	l1, err := net.Listen("tcp", fmt.Sprintf(":%d", s.port1))
	if err != nil {
		log.Fatal("Cannot starting listening to the port: ", err)
	}
	l2, err := net.Listen("tcp", fmt.Sprintf(":%d", s.port2))
	if err != nil {
		log.Fatal("Cannot starting listening to the port: ", err)
	}
	go rpcServer1.Accept(l1)
	go rpcServer2.Accept(l2)
	s.connectServers()
	fmt.Println("Starting server", *id)
	s.runHandlers()
	fmt.Println("Handler running", *id)

	Wait()
}
开发者ID:Consequences,项目名称:riffle,代码行数:59,代码来源:server.go

示例2: testRPCClient

// testRPCClient returns an RPCClient connected to an RPC server that
// serves only this connection.
func testRPCClient(t *testing.T) (*RPCClient, *Agent) {
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	agent := testAgent()
	server := rpc.NewServer()
	if err := registerEndpoint(server, agent); err != nil {
		l.Close()
		t.Fatalf("err: %s", err)
	}

	go func() {
		conn, err := l.Accept()
		l.Close()
		if err != nil {
			t.Fatalf("err: %s", err)
		}
		defer conn.Close()
		server.ServeConn(conn)
	}()

	rpcClient, err := rpc.Dial("tcp", l.Addr().String())
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	return &RPCClient{Client: rpcClient}, agent
}
开发者ID:johnbellone,项目名称:serf,代码行数:32,代码来源:rpc_client_test.go

示例3: TestSend

func TestSend(t *testing.T) {
	client, server := net.Pipe()
	go doServiceHandshake(server, true, t)

	cn, err := NewConnectionFromNetConn("TestRPCService", client)
	c := cn.(*Conn)

	s := rpc.NewServer()
	var ts TestRPCService
	s.Register(&ts)
	go s.ServeCodec(bsonrpc.NewServerCodec(server))

	var tp TestParam
	tp.Val1 = "Hello World"
	tp.Val2 = 10

	ri := &skynet.RequestInfo{}

	ts.TestMethod = func(in skynet.ServiceRPCIn, out *skynet.ServiceRPCOut) (err error) {
		out.Out, err = bson.Marshal(&tp)

		var t TestParam

		if err != nil {
			return
		}

		if in.ClientID != c.clientID {
			return errors.New("Failed to set ClientID on request")
		}

		if in.Method != "Foo" {
			return errors.New("Failed to set Method on request")
		}

		if *in.RequestInfo != *ri {
			return errors.New("Failed to set RequestInfo on request")
		}

		err = bson.Unmarshal(in.In, &t)
		if err != nil {
			return
		}

		if t.Val1 != tp.Val1 || tp.Val2 != tp.Val2 {
			return errors.New("Request failed to send proper data")
		}

		return
	}

	err = c.Send(ri, "Foo", tp, &tp)
	if err != nil {
		t.Error(err)
		return
	}

	c.Close()
	server.Close()
}
开发者ID:bubble66,项目名称:skynet,代码行数:60,代码来源:connection_test.go

示例4: NewServer

func NewServer(config *Config) (*Server, error) {
	s := &Server{
		config:     config,
		eventChLAN: make(chan serf.Event, 256),
		rpcServer:  rpc.NewServer(),
		shutdownCh: make(chan struct{}),
		ambari:     &Ambari{config.AmbariConfig},
	}

	// Get hosts
	hosts, err := NewHostsManager(config.HostsFile)
	if err != nil {
		return nil, err
	}
	s.hosts = hosts
	go s.updateHosts()

	// Setup serf
	serfLAN, err := s.setupSerf()
	if err != nil {
		s.Shutdown()
		return nil, err
	}
	s.serfLAN = serfLAN
	go s.serfEventHandler()

	// Setup RPC and start listening for requests
	if err := s.setupRPC(); err != nil {
		s.Shutdown()
		return nil, err
	}
	go s.listenRPC()

	return s, nil
}
开发者ID:cskksc,项目名称:sr6,代码行数:35,代码来源:server.go

示例5: StartRpc

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
}
开发者ID:fantasycool,项目名称:spread_compute,代码行数:28,代码来源:producer.go

示例6: NewSuperServiceServer

// NewSuperServiceServer returns a new SuperService Server.
func NewSuperServiceServer(x SuperService) *rpc.Server {
	srv := rpc.NewServer()
	if err := srv.RegisterName("SuperService", x); err != nil {
		log.Fatal(err)
	}
	return srv
}
开发者ID:playnb,项目名称:mustang,代码行数:8,代码来源:message.pb.go

示例7: BenchmarkNetrpcByteSlice

func BenchmarkNetrpcByteSlice(b *testing.B) {
	connC, connS := getTcpPipe(b)
	defer connC.Close()
	defer connS.Close()

	s := rpc.NewServer()
	if err := s.Register(&NetrpcService{}); err != nil {
		b.Fatalf("Error when registering rpc service: %s", err)
	}
	go s.ServeConn(connS)

	c := rpc.NewClient(connC)
	defer c.Close()

	req := []byte("byte slice byte slice aaa bbb ccc foobar")
	b.SetParallelism(250)
	b.ResetTimer()
	b.RunParallel(func(pb *testing.PB) {
		var resp []byte
		for i := 0; pb.Next(); i++ {
			if err := c.Call("NetrpcService.ByteSlice", req, &resp); err != nil {
				b.Fatalf("Unexpected error when calling NetrpcService.ByteSlice(%q): %s", req, err)
			}
			if !bytes.Equal(resp, req) {
				b.Fatalf("Unexpected response: %q. Expected %q", resp, req)
			}
		}
	})
}
开发者ID:running-fish,项目名称:gorpc,代码行数:29,代码来源:bench_test.go

示例8: TestArtifactRPC

func TestArtifactRPC(t *testing.T) {
	// Create the interface to test
	a := new(testArtifact)

	// Start the server
	server := rpc.NewServer()
	RegisterArtifact(server, a)
	address := serveSingleConn(server)

	// Create the client over RPC and run some methods to verify it works
	client, err := rpc.Dial("tcp", address)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	aClient := Artifact(client)

	// Test
	if aClient.BuilderId() != "bid" {
		t.Fatalf("bad: %s", aClient.BuilderId())
	}

	if !reflect.DeepEqual(aClient.Files(), []string{"a", "b"}) {
		t.Fatalf("bad: %#v", aClient.Files())
	}

	if aClient.Id() != "id" {
		t.Fatalf("bad: %s", aClient.Id())
	}

	if aClient.String() != "string" {
		t.Fatalf("bad: %s", aClient.String())
	}
}
开发者ID:englishm,项目名称:packer,代码行数:33,代码来源:artifact_test.go

示例9: PostProcess

func (p *postProcessor) PostProcess(ui packer.Ui, a packer.Artifact) (packer.Artifact, bool, error) {
	server := rpc.NewServer()
	RegisterArtifact(server, a)
	RegisterUi(server, ui)

	var response PostProcessorProcessResponse
	if err := p.client.Call("PostProcessor.PostProcess", serveSingleConn(server), &response); err != nil {
		return nil, false, err
	}

	if response.Err != nil {
		return nil, false, response.Err
	}

	if response.RPCAddress == "" {
		return nil, false, nil
	}

	client, err := rpc.Dial("tcp", response.RPCAddress)
	if err != nil {
		return nil, false, err
	}

	return Artifact(client), response.Keep, nil
}
开发者ID:B-Rich,项目名称:packer,代码行数:25,代码来源:post_processor.go

示例10: runServer

func runServer(ch chan bool, done chan bool) {
	cert, err := tls.LoadX509KeyPair("../cert.pem", "../key.pem")
	if err != nil {
		log.Fatalf("While loading tls certs: %v", err)
		return
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}}
	ln, err := tls.Listen("tcp", addr, &config)
	if err != nil {
		log.Fatalf("When listening: %v", err)
		return
	}
	s := rpc.NewServer()
	if err := s.Register(&PostingList{}); err != nil {
		log.Fatalf("Error when registering rpc server: %v", err)
		return
	}

	ch <- true
	log.Debugln("Ready to accept new connection")
	conn, err := ln.Accept()
	if err != nil {
		log.Fatalf("cannot accept incoming tcp conn: %s", err)
		return
	}
	defer conn.Close()
	log.Debugln("Accepted a connection")
	go s.ServeConn(conn)
	<-done
}
开发者ID:dgraph-io,项目名称:experiments,代码行数:30,代码来源:main.go

示例11: listenAndServeEchoService

func listenAndServeEchoService(network, addr string,
	serveConn func(srv *rpc.Server, conn io.ReadWriteCloser)) (net.Listener, error) {
	l, err := net.Listen(network, addr)
	if err != nil {
		fmt.Printf("failed to listen on %s: %s\n", addr, err)
		return nil, err
	}
	srv := rpc.NewServer()
	if err := srv.RegisterName("EchoService", new(Echo)); err != nil {
		return nil, err
	}
	go func() {
		for {
			conn, err := l.Accept()
			if err != nil {
				log.Infof("accept: %v\n", err)
				break
			}
			serveConn(srv, conn)
		}
	}()

	if *onlyEchoServer {
		select {}
	}
	return l, nil
}
开发者ID:husttom,项目名称:cockroach,代码行数:27,代码来源:rpc_test.go

示例12: main

func main() {
	newServer := rpc.NewServer()
	newServer.Register(new(Arith))

	l, e := net.Listen("tcp", "127.0.0.1:1234")
	if e != nil {
		log.Fatalf("net.Listen tcp :0:%v", e)
	}

	go newServer.Accept(l)
	newServer.HandleHTTP("/foo", "/bar")
	time.Sleep(2 * time.Second)

	address, err := net.ResolveTCPAddr("tcp", "127.0.0.1:1234")
	if err != nil {
		panic(err)
	}
	conn, _ := net.DialTCP("tcp", nil, address)
	defer conn.Close()

	client := rpc.NewClient(conn)
	defer client.Close()

	args := &Args{7, 8}
	reply := make([]string, 10)
	err = client.Call("Arith.Multiply", args, &reply)
	if err != nil {
		log.Fatal("arith error: ", err)
	}
	log.Println(reply)
}
开发者ID:bonly,项目名称:exercise,代码行数:31,代码来源:20111030_new_rpc.go

示例13: StartServer

func StartServer(hostname string, hd *hood.Hood) *Master {
	// call gob.Register on structures you want
	// Go's RPC library to marshall/unmarshall.
	// gob.Register()

	gopath := os.Getenv("GOPATH")
	if _, err := os.Stat(gopath + "/src/segments"); err != nil {
		if os.IsNotExist(err) {
			os.Mkdir(gopath+"/src/segments", 0777)
		} else {
			panic(err)
		}
	}

	master := new(Master)

	master.hd = hd
	master.events = make(chan (Event), MAX_EVENTS)
	master.minWorkers = 1

	rpcs := rpc.NewServer()
	rpcs.Register(master)

	// ignore the domain name: listen on all urls
	splitName := strings.Split(hostname, ":")
	l, e := net.Listen("tcp", ":"+splitName[1])
	if e != nil {
		log.Fatal("listen error: ", e)
	}
	master.l = l

	// Recovery procedure
	tx := master.hd.Begin()
	master.getNumAliveWorkers(tx)
	commitOrPanic(tx)
	master.restartPendingRdds()

	// start event loop
	go master.eventLoop()

	go func() {
		for {
			if conn, err := master.l.Accept(); err == nil {
				go rpcs.ServeConn(conn)
			} else {
				master.kill()
			}
		}
	}()

	// create a thread to call tick() periodically.
	go func() {
		for {
			master.tick()
			time.Sleep(TickInterval)
		}
	}()

	return master
}
开发者ID:jtwarren,项目名称:Hurricane,代码行数:60,代码来源:master.go

示例14: Make

//
// the application wants to create a paxos peer.
// the ports of all the paxos peers (including this one)
// are in peers[]. this servers port is peers[me].
//
func Make(peers []string, me int, rpcs *rpc.Server) *Paxos {
	px := &Paxos{}
	px.peers = peers
	px.me = me

	// Your initialization code here.

	if rpcs != nil {
		// caller will create socket &c
		rpcs.Register(px)
	} else {
		rpcs = rpc.NewServer()
		rpcs.Register(px)

		// prepare to receive connections from clients.
		// change "unix" to "tcp" to use over a network.
		os.Remove(peers[me]) // only needed for "unix"
		l, e := net.Listen("unix", peers[me])
		if e != nil {
			log.Fatal("listen error: ", e)
		}
		px.l = l

		// please do not change any of the following code,
		// or do anything to subvert it.

		// create a thread to accept RPC connections
		go func() {
			for px.dead == false {
				conn, err := px.l.Accept()
				if err == nil && px.dead == false {
					if px.unreliable && (rand.Int63()%1000) < 100 {
						// discard the request.
						conn.Close()
					} else if px.unreliable && (rand.Int63()%1000) < 200 {
						// process the request but force discard of reply.
						c1 := conn.(*net.UnixConn)
						f, _ := c1.File()
						err := syscall.Shutdown(int(f.Fd()), syscall.SHUT_WR)
						if err != nil {
							fmt.Printf("shutdown: %v\n", err)
						}
						px.rpcCount++
						go rpcs.ServeConn(conn)
					} else {
						px.rpcCount++
						go rpcs.ServeConn(conn)
					}
				} else if err == nil {
					conn.Close()
				}
				if err != nil && px.dead == false {
					fmt.Printf("Paxos(%v) accept: %v\n", me, err.Error())
				}
			}
		}()
	}

	return px
}
开发者ID:kedebug,项目名称:golang-programming,代码行数:65,代码来源:paxos.go

示例15: main

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)
}
开发者ID:grd,项目名称:go-ipc-example,代码行数:35,代码来源:server-example.go


注:本文中的net/rpc.NewServer函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。