首页 > 其他 > 详细

一对一聊天(二)

时间:2019-03-25 17:12:26      阅读:44      评论:0      收藏:0      [点我收藏+]

标签: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"}

技术分享图片

一对一聊天(二)

标签:tle   get   list   pen   true   握手   output   cli   server   

原文:https://blog.51cto.com/5660061/2368838

(0)
(0)
   
举报
评论 一句话评论(0
0条