server.go
server发送当前时间
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
var up = websocket.Upgrader{}
func echo(w http.ResponseWriter, r *http.Request) {
conn, err := up.Upgrade(w, r, nil)
if err != nil {
log.Println("upgrade failed,err:", err)
return
}
defer conn.Close()
for {
t := time.Now()
err := conn.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
log.Println("write msg failed,err:", err)
return
}
}
}
func main() {
fmt.Println("server start...")
http.HandleFunc("/echo", echo)
err := http.ListenAndServe("localhost:8888", nil)
if err != nil {
log.Println("listen host and port failed,err:", err)
return
}
fmt.Println("server end...")
}
client.go
接受server发来的消息
package main
import (
"fmt"
"log"
"github.com/gorilla/websocket"
)
func main() {
conn, _, err := websocket.DefaultDialer.Dial("ws://127.0.0.1:8888/echo", nil)
if err != nil {
log.Println("connect failed,err:", err)
return
}
defer conn.Close()
for {
_, msg, err := conn.ReadMessage()
if err != nil {
log.Println("read msg failed ,err:", err)
break
}
fmt.Println(string(msg))
}
}