mirror of
https://github.com/kataras/iris.git
synced 2025-12-23 12:57:05 +00:00
add iris websocket client side for Go and a simple chat example
Former-commit-id: af1c555b6b092a3d0484fee2e200fd8767d7239e
This commit is contained in:
58
_examples/websocket/go-client/client/main.go
Normal file
58
_examples/websocket/go-client/client/main.go
Normal file
@@ -0,0 +1,58 @@
|
||||
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() {
|
||||
conn, err := websocket.Dial(url, websocket.DefaultEvtMessageKey)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
conn.OnError(func(err error) {
|
||||
fmt.Printf("error: %v", err)
|
||||
})
|
||||
|
||||
conn.OnDisconnect(func() {
|
||||
fmt.Println("Server was force-closed[see ../server/main.go#L19] this connection after 20 seconds, therefore I am disconnected.")
|
||||
os.Exit(0)
|
||||
})
|
||||
|
||||
conn.On("chat", func(message string) {
|
||||
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
|
||||
}
|
||||
|
||||
conn.Emit("chat", msgToSend)
|
||||
}
|
||||
|
||||
fmt.Println("Terminated.")
|
||||
}
|
||||
32
_examples/websocket/go-client/server/main.go
Normal file
32
_examples/websocket/go-client/server/main.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/kataras/iris/websocket"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
ws := websocket.New(websocket.Config{})
|
||||
app.Get("/socket", ws.Handler())
|
||||
|
||||
ws.OnConnection(func(c websocket.Connection) {
|
||||
go func() {
|
||||
<-time.After(20 * time.Second)
|
||||
c.Disconnect()
|
||||
}()
|
||||
|
||||
c.On("chat", func(message string) {
|
||||
c.To(websocket.Broadcast).Emit("chat", c.ID()+": "+message)
|
||||
})
|
||||
|
||||
c.OnDisconnect(func() {
|
||||
fmt.Printf("Connection with ID: %s has been disconnected!\n", c.ID())
|
||||
})
|
||||
})
|
||||
|
||||
app.Run(iris.Addr(":8080"))
|
||||
}
|
||||
Reference in New Issue
Block a user