go-xmpp/_examples/xmpp_echo/xmpp_echo.go

57 lines
1.2 KiB
Go
Raw Normal View History

/*
xmpp_echo is a demo client that connect on an XMPP server and echo message received back to original sender.
*/
package main
import (
"fmt"
"log"
"os"
"gosrc.io/xmpp"
"gosrc.io/xmpp/stanza"
)
func main() {
2018-09-26 14:25:04 +00:00
config := xmpp.Config{
TransportConfiguration: xmpp.TransportConfiguration{
2019-10-29 13:39:58 +00:00
Address: "localhost:5222",
},
2018-01-26 08:55:39 +00:00
Jid: "test@localhost",
Credential: xmpp.Password("test"),
StreamLogger: os.Stdout,
2018-01-26 08:55:39 +00:00
Insecure: true,
// TLSConfig: tls.Config{InsecureSkipVerify: true},
2018-01-26 08:55:39 +00:00
}
2019-06-18 10:37:16 +00:00
router := xmpp.NewRouter()
2019-06-19 09:19:49 +00:00
router.HandleFunc("message", handleMessage)
2019-06-18 10:37:16 +00:00
2020-03-06 15:44:01 +00:00
client, err := xmpp.NewClient(&config, router, errorHandler)
2018-09-23 16:40:13 +00:00
if err != nil {
log.Fatalf("%+v", err)
}
2019-06-07 14:30:57 +00:00
// If you pass the client to a connection manager, it will handle the reconnect policy
// for you automatically.
cm := xmpp.NewStreamManager(client, nil)
2019-06-18 10:37:16 +00:00
log.Fatal(cm.Run())
}
func handleMessage(s xmpp.Sender, p stanza.Packet) {
msg, ok := p.(stanza.Message)
2019-06-18 10:37:16 +00:00
if !ok {
_, _ = fmt.Fprintf(os.Stdout, "Ignoring packet: %T\n", p)
return
}
2019-06-18 10:37:16 +00:00
_, _ = fmt.Fprintf(os.Stdout, "Body = %s - from = %s\n", msg.Body, msg.From)
reply := stanza.Message{Attrs: stanza.Attrs{To: msg.From}, Body: msg.Body}
2019-06-18 10:37:16 +00:00
_ = s.Send(reply)
}
func errorHandler(err error) {
fmt.Println(err.Error())
}