2019-02-09 03:28:00 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/kataras/iris/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
url = "ws://localhost:8080/socket"
|
|
|
|
prompt = ">> "
|
|
|
|
)
|
|
|
|
|
|
|
|
/*
|
|
|
|
How to run:
|
|
|
|
Start the server, if it is not already started by executing `go run ../server/main.go`
|
|
|
|
And open two or more terminal windows and start the clients:
|
|
|
|
$ go run main.go
|
|
|
|
>> hi!
|
|
|
|
*/
|
|
|
|
func main() {
|
2019-02-19 21:49:16 +01:00
|
|
|
c, err := websocket.Dial(nil, url, websocket.ConnectionConfig{})
|
2019-02-09 03:28:00 +01:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2019-02-10 16:16:43 +01:00
|
|
|
c.OnError(func(err error) {
|
2019-02-09 03:28:00 +01:00
|
|
|
fmt.Printf("error: %v", err)
|
|
|
|
})
|
|
|
|
|
2019-02-10 16:16:43 +01:00
|
|
|
c.OnDisconnect(func() {
|
|
|
|
fmt.Println("Server was force-closed[see ../server/main.go#L17] this connection after 20 seconds, therefore I am disconnected.")
|
2019-02-09 03:28:00 +01:00
|
|
|
os.Exit(0)
|
|
|
|
})
|
|
|
|
|
2019-02-10 16:16:43 +01:00
|
|
|
c.On("chat", func(message string) {
|
2019-02-09 03:28:00 +01:00
|
|
|
fmt.Printf("\n%s\n", message)
|
|
|
|
})
|
|
|
|
|
|
|
|
fmt.Println("Start by typing a message to send")
|
|
|
|
scanner := bufio.NewScanner(os.Stdin)
|
|
|
|
for {
|
|
|
|
fmt.Print(prompt)
|
|
|
|
if !scanner.Scan() || scanner.Err() != nil {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
msgToSend := scanner.Text()
|
|
|
|
if msgToSend == "exit" {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2019-02-10 16:16:43 +01:00
|
|
|
c.Emit("chat", msgToSend)
|
2019-02-09 03:28:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println("Terminated.")
|
|
|
|
}
|