Beispiel #1
0
func main() {
	client := roster.NewClient(roster.ClientConfig{})

	// Send a message every 3 seconds
	for {
		service, err := client.Discover("echo")
		if err == roster.ErrRegistryNotActive || err == roster.ErrServiceNotFound {
			// Waiting for registry to become active - in production would probably want to only retry N number of times
			continue
		} else if err != nil {
			log.Fatalln(err)
		}

		u, err := url.Parse(service.Endpoint)
		if err != nil {
			log.Fatal(err)
		}

		strEcho := "Hello echo service\n"

		tcpAddr, err := net.ResolveTCPAddr("tcp", u.Host)
		if err != nil {
			log.Fatal(err)
		}

		conn, err := net.DialTCP("tcp", nil, tcpAddr)
		if err != nil {
			log.Fatal(err)
		}

		_, err = conn.Write([]byte(strEcho))
		if err != nil {
			log.Fatal(err)
		}

		log.Println("Write to server = ", strEcho)

		reply := make([]byte, 1024)

		_, err = conn.Read(reply)
		if err != nil {
			log.Fatal(err)
		}

		log.Println("Reply from server=", string(reply))

		conn.Close()

		time.Sleep(3 * time.Second)
	}

}
Beispiel #2
0
func main() {
	client := roster.NewClient(roster.ClientConfig{})

	CONN_HOST, err := client.GetLocalIP()
	if err != nil {
		log.Fatalln(err)
	}

	endpoint := &url.URL{Scheme: CONN_TYPE, Host: CONN_HOST + ":" + CONN_PORT}

	service, err := client.Register("echo", endpoint.String())
	if err != nil {
		log.Fatalln(err)
	}

	ln, err := net.Listen(CONN_TYPE, ":"+CONN_PORT)
	if err != nil {
		log.Fatalln(err)
		return
	}
	defer ln.Close()
	log.Printf("Listening on %s:%s\n", CONN_HOST, CONN_PORT)

	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		<-sigs
		log.Println("Unregistering service")
		service.Unregister()
		os.Exit(1)
	}()

	for {
		conn, _ := ln.Accept()
		go func(conn net.Conn) {

			//logs an incoming message
			log.Printf("Received message %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())
			reader := bufio.NewReader(conn)
			for {
				line, err := reader.ReadBytes('\n')
				if err != nil { // EOF, or worse
					break
				}
				conn.Write(line)
			}
		}(conn)
	}
}