一對一聊天(二)
阿新 • • 發佈:2019-03-25
tle get list pen true 握手 output cli server
package main
import (
"github.com/gorilla/websocket"
"net/http"
"log"
)
var (
PushMessage = make(chan message, 100)
Clients = make(map[string] *websocket.Conn)
)
var (
// http升級websocket協議的配置
upgrader = websocket.Upgrader{
// 允許所有CORS跨域請求
CheckOrigin: func(r *http.Request) bool {
return true
},
}
)
//消息結構
type message struct {
From string //發送人id
To string //接收人id
Sess string //session的id
Msg string //消息內容
}
func wsHandler(writer http.ResponseWriter, request *http.Request) {
var (
ws *websocket.Conn
err error
)
//完成握手應答
if ws, err = upgrader.Upgrade(writer, request, nil); err != nil {
return
}
//收數據
for {
var msg message
err = ws.ReadJSON(&msg)
//log.Printf("From: %v", msg.From)
if err != nil {
//log.Printf("error1: %v", err)
//delete(Clients, msg.From)
return
}
Clients[msg.From] = ws
PushMessage <- msg
}
defer ws.Close()
}
func toMessage() {
for {
msg := <-PushMessage
if _, ok := Clients[msg.To]; ok {
err := Clients[msg.To].WriteJSON(msg.Msg)
if err != nil {
log.Printf("err2:%v", err)
}
}
}
}
func main() {
http.HandleFunc("/ws", wsHandler)
log.Println("server :9988")
go toMessage()
err := http.ListenAndServe(":9988", nil)
if err != nil {
panic(err)
}
}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>websocket測試程序 </title> <script> window.addEventListener("load", function (evt) { var output = document.getElementById("output"); var input = document.getElementById("input") var ws; var print = function (message) { var d = document.createElement("div"); d.innerHTML = message; output.appendChild(d); }; document.getElementById("open").onclick = function (ev) { if (ws) { return false; } ws = new WebSocket("ws://127.0.0.1:9988/ws"); ws.onopen = function (ev) { print("連接成功"); }; ws.onclose = function (ev) { print("連接關閉"); }; ws.onerror = function (ev) { print("發生錯誤 " + ev.data) }; ws.onmessage = function (ev1) { print("服務端消息: " + ev1.data) }; return false }; document.getElementById("send").onclick = function (ev) { if (!ws) { return false } if (input.value !== "") { ws.send(input.value) } else { print("發送內容不能為空") } }; document.getElementById("close").onclick = function (ev) { if (ws) { ws.close() } } }) </script> </head> <body> <div> <br> websocket測試程序,消息又客戶端發送到server然後原封不動的返回,server使用go實現 <br> <br> <br> <input type="button" value="連接" id="open"> <input placeholder="輸入要發送的消息..." id="input"> <input type="button" value="發送" id="send"> <input type="button" value="關閉" id="close"> </div> <div id="output"> </div> </body> </html>
打開兩個頁面:
一個發送:{"From":"666","To":"888","Sess":"sess_666","msg":"hello 666"}
一個發送:{"From":"888","To":"666","Sess":"sess_888","msg":"hello 888"}
一對一聊天(二)