最近需要做一个消息通知的推送,开始在实践 websocket
server port:9091
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
} // use default options
func Echo(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
mt, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
err = c.WriteMessage(mt, message)
if err != nil {
log.Println("write:", err)
break
}
}}
func main() {
http.HandleFunc("/echo", Echo)
fmt.Println("start server port:9091")
if err := http.ListenAndServe(":9091", nil); err != nil {
log.Fatal("ListenAndServe:1234:", err)
}}
client:
<!DOCTYPE html>
<html>
<head>
<title>websocket</title>
</head>
<body>
<h1>Echo Test</h1>
<input type="text" id="sendTxt">
<button id="sendBtn">发送</button>
<div id="recv"></div>
<script type="text/javascript">
let ws = new WebSocket("ws://127.0.0.1:9091/echo")
ws.onopen = function () {
// body...
console.log("websocket open");
document.getElementById('recv').innerHTML = 'Connected';
}
ws.oncolse = function (e) {
// body...
console.log("consoled");
}
ws.onmessage=function (e) {
// body...
console.log(e.data)
document.getElementById('recv').innerHTML = e.data;
}
document.getElementById('sendBtn').onclick=function(){
var txt=document.getElementById('sendTxt').value;
console.log(txt)
ws.send(txt)
}
</script>
</body>
</html>
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于