golang achieve websocket

1. The need websocket package: 
"github.com/gorilla/websocket"
main Package 

Import ( 
	"github.com/gorilla/websocket" 
	"learngo / WebSocket / impl" 
	"NET / HTTP" 
	"Time" 
) 

var ( 
	Upgrader websocket.Upgrader = { 
		// allow cross-domain access 
		CheckOrigin: func (r * http .request) {BOOL 
			return to true 
		}, 
	} 
) 

FUNC wsHandler (http.ResponseWriter W, R & lt http.Request *) { 
	//w.Write([]byte("hello ")) 
	// http request is received (upgrade) complete protocol conversion websocket 
	// put in the header of the response upgrade: websoket 
	var ( 
		wsConn websocket.Conn * 
		ERR error 
		Data [] byte 
		Conn impl.Connection * 
	)  
	// upgrade websocket (message back to the client)
	IF wsConn, upgrader.Upgrade ERR = (W, R & lt, nil ); err!=nil {
		//报错了,直接返回底层的websocket链接就会终断掉
		return
	}
	if conn, err = impl.InitConnection(wsConn); err != nil {
		goto ERR
	}

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

	}()

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

func userHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World!"))
}

func main() {
	//http://localhost:7777/ws
	http.HandleFunc("/ws", wsHandler)
	http.HandleFunc("/user", userHandler)
	//服务端启动
	http.ListenAndServe("0.0.0.0:7777", nil)
}

 

Implement the module: thread-safe

main Package 

Import ( 
	"github.com/gorilla/websocket" 
	"NET / HTTP" 
) 

var ( 
	Upgrader websocket.Upgrader = { 
		// allow cross-domain access 
		CheckOrigin: FUNC (R & lt http.Request *) {BOOL 
			return to true 
		}, 
	} 
) 

FUNC wsHandler (http.ResponseWriter W, R & lt http.Request *) { 
	//w.Write([]byte("hello ")) 
	// http request is received (upgrade), protocol conversion is completed websocket 
	// in response placed in the header upgrade: websoket 
	var ( 
		Conn websocket.Conn * 
		ERR error 
		// int msgType 
		Data [] byte 
	) 
	! IF Conn, upgrader.Upgrade ERR = (W, R & lt, nil); ERR = nil { 
		// given a directly back to the bottom end websocket broken link will 
		return 
	} 
	// get the object websocket.Conn long link, data transmission and reception 
	for { 
		// the Text (JSON), Binary 
		// _ IF, Data, ERR = conn.ReadMessage (); ERR = nil {! 
		IF _, data, ERR = conn.ReadMessage ();! ERR = nil { 
			// given off WebSocket 
			GOTO ERR 
		} 
		// send data, determines whether the return value error 
		if err = conn.WriteMessage (websocket.TextMessage, data );! err = {nil 
			// given a 
			GOTO ERR 
		} 
	} 
tag // error of 
ERR: 
	conn.Close () 
} 

FUNC of HelloHandler (http.ResponseWriter W, R & lt http.Request *) { 
	w.Write ([] byte ( "the Hello World! ")) 
} 

FUNC main () { 
	// HTTP: // localhost: 7777 / WS 
	http.HandleFunc (" / WS ", wsHandler)
	http.HandleFunc ( "/ Hello", of HelloHandler)
	// server side, start 
	http.ListenAndServe ( "0.0.0.0:7777", nil) 
}

 js file:

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <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(evt) {
                if (ws) {
                    return false;
                }
                ws = new WebSocket("ws://192.168.230.130:7777/ws");
                ws.onopen = function(evt) {
                    print("OPEN");
                }
                ws.onclose = function(evt) {
                    print("CLOSE");
                    ws = null;
                }
                ws.onmessage = function(evt) {
                    print("RESPONSE: " + evt.data);
                }
                ws.onerror = function(evt) {
                    print("ERROR: " + evt.data);
                }
                return false;
            };
            document.getElementById("send").onclick = function(evt) {
                if (!ws) {
                    return false;
                }
                print("SEND: " + input.value);
                ws.send(input.value);
                return false;
            };
            document.getElementById("close").onclick = function(evt) {
                if (!ws) {
                    return false;
                }
                ws.close();
                return false;
            };
        });
    </script>
</head>
<body>
<table>
    <tr><td valign="top" width="50%">
        <p>Click "Open" to create a connection to the server,
            "Send" to send a message to the server and "Close" to close the connection.
            You can change the message and send multiple times.
        </p>
            <form>
                <button id="open">Open</button>
                <button id="close">Close</button>
            <input id="input" type="text" value="Hello world!">
            <button id="send">Send</button>
            </form>
    </td><td valign="top" width="50%">
        <div id="output"></div>
    </td></tr></table>
</body>
</html>

  

  

Guess you like

Origin www.cnblogs.com/xingyunshizhe/p/11225135.html