웹소켓 사례

5512 단어 인터넷
브라우저 클라이언트:



    
    websocket  
    
        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:8888/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()
                }
            }

        })

    




websocket , server ,server go



버전 1:
package main

import (
    "net/http"
    "github.com/gorilla/websocket"
)

var (
    // http websocket 
    upgrader = websocket.Upgrader{
        //  CORS 
        CheckOrigin: func(r *http.Request) bool {
            return true
        },
    }
)

func wsHandler(writer http.ResponseWriter, request *http.Request) {
    var (
        conn *websocket.Conn
        err error
        //msgType int
        data []byte
    )
    // 
    if conn, err = upgrader.Upgrade(writer, request, nil); err != nil {
        return
    }

    // 
    for {
        // text、binary, text
        if _, data, err = conn.ReadMessage(); err != nil {
            goto ERR
        }
        if err = conn.WriteMessage(websocket.TextMessage, data); err != nil {
            goto ERR
        }
    }
ERR:
    conn.Close()

}

func main() {
    http.HandleFunc("/ws", wsHandler)
    http.ListenAndServe("127.0.0.1:8888", nil)
}

버전 1 최적화되지 않음
버전 2:
connection.go:
package impl

import (
    "github.com/gorilla/websocket"
    "sync"
    "errors"
)

type Connection struct {
    wsConn *websocket.Conn   //  websocket
    inChan chan []byte      //  
    outChan chan []byte     //   
    closeChan chan byte    //  
    isClosed bool
    mutex sync.Mutex       //  
}

// websocket 
func InitConnection(wsConn *websocket.Conn) (conn *Connection, err error) {
    conn = &Connection{
        wsConn: wsConn,
        inChan: make(chan []byte, 1000),
        outChan: make(chan []byte, 1000),
        closeChan: make(chan byte, 1),
    }

    // 
    go conn.readLoop()

    // 
    go conn.writeLoop()

    return
}

func (conn *Connection) ReadMessage() (data []byte, err error) {
    select {
    case data = 

server.go:
package main

import (
    "net/http"
    "github.com/gorilla/websocket"
    "./impl"
    "time"
)

var (
    // http websocket 
    upgrader = websocket.Upgrader{
        //  CORS 
        CheckOrigin: func(r *http.Request) bool {
            return true
        },
    }
)

func wsHandler(writer http.ResponseWriter, request *http.Request) {
    var (
        wsConn *websocket.Conn
        err error
        //msgType int
        data []byte
        conn *impl.Connection
    )
    // 
    if wsConn, err = upgrader.Upgrade(writer, request, nil); err != nil {
        return
    }

    if conn, err = impl.InitConnection(wsConn); err != nil {
        goto ERR
    }

    //  
    go func() {
        var (
            err error
        )
        for {
            if err = conn.WriteMessage([]byte("heartbeat")); err != nil {
                return
            }
            time.Sleep(time.Second)
        }
    }()

    for {
        if data, err = conn.ReadMessage(); err != nil {
            goto ERR
        }
        if err = conn.WriteMessage(data); err != nil {
            goto ERR
        }
    }

ERR:
    //  
    conn.Close()

    /*// 
    for {
        // text、binary, text
        if _, data, err = conn.ReadMessage(); err != nil {
            goto ERR
        }
        if err = conn.WriteMessage(websocket.TextMessage, data); err != nil {
            goto ERR
        }
    }
ERR:
    conn.Close()*/

}

func main() {
    http.HandleFunc("/ws", wsHandler)
    http.ListenAndServe("127.0.0.1:8888", nil)
}

포장을 해서 라인이 안전하다
다음으로 전송:https://blog.51cto.com/5660061/2361096

좋은 웹페이지 즐겨찾기