Exemplo n.º 1
0
// Listen starts ServiceDirectory listening for incoming connections
func (dir *ServiceDirectory) Listen(addr string) error {
	var err = dir.server.Listen(addr)
	if err != nil {
		return err
	}

	// keep alive
	var timeout = gomsg.NewTimeout(dir.PingInterval, dir.PingInterval*time.Duration(dir.PingFailures), func(o interface{}) {
		c := o.(net.Conn)

		fmt.Println("I: < Dir: Ping timeout. Purging/killing connection from", c.RemoteAddr())
		dir.server.Kill(c)
	})
	dir.server.OnConnect = func(w *gomsg.Wired) {
		// starts monitoring
		timeout.Delay(w.Conn())
	}
	// reply to pings and delays the timeout
	dir.server.Handle(PING, func(r *gomsg.Request) string {
		timeout.Delay(r.Connection())

		return PONG
	})

	return nil
}
Exemplo n.º 2
0
func main() {
	server := gomsg.NewServer()
	// keep alive
	var timeout = gomsg.NewTimeout(CLEAN_CYCLE, time.Second, func(o interface{}) {
		c := o.(net.Conn)
		fmt.Println("=====> killing connection from", c.RemoteAddr())
		server.Wires.Kill(c)
	})

	server.OnConnect = func(w *gomsg.Wired) {
		// starts monitoring
		timeout.Delay(w.Conn())
	}
	// for PING messages the server will reply immediatly,
	// without relaying the message to the clients.
	server.Route("*", time.Second,
		func(ctx *gomsg.Request) bool {
			// any message received, delays the timeout
			timeout.Delay(ctx.Connection())

			if ctx.Name == "PING" {
				ctx.SetReply([]byte("PONG"))
				return false
			}

			return true
		},
		nil)

	server.Listen(":7777")

	cli := gomsg.NewClient()
	cli.SetReconnectInterval(0)
	cli.Handle("HELLO", func(ctx *gomsg.Request, m string) (string, error) {
		fmt.Println("<=== [1] processing:", m, "from", ctx.Connection().RemoteAddr())
		return fmt.Sprintf("[1] Hello %s", m), nil
	})
	cli.Connect("localhost:7777")

	// just to get in the way
	cli3 := gomsg.NewClient()
	cli3.SetReconnectInterval(0)
	cli3.Connect("localhost:7777")

	cli2 := gomsg.NewClient()
	cli2.SetReconnectInterval(0)
	cli2.Handle("HELLO", func(ctx *gomsg.Request, m string) (string, error) {
		fmt.Println("<=== [2] processing:", m, "from", ctx.Connection().RemoteAddr())
		return fmt.Sprintf("[2] Hello %s", m), nil
	})
	cli2.Connect("localhost:7777")

	<-cli3.RequestAll("HELLO", "World!", func(ctx gomsg.Response, r string, e error) {
		fmt.Println("===HELLO===> reply:", r, e, "from", ctx.Connection().RemoteAddr())
	})

	time.Sleep(time.Millisecond * 2000)
	<-cli3.RequestAll("HELLO", "World!", func(ctx gomsg.Response, r string, e error) {
		fmt.Println("===HELLO===> reply:", r, e, "from", ctx.Connection().RemoteAddr())
	})

	time.Sleep(time.Millisecond * 1000)
}