创建websocket实例go get -u github.com/gorilla/websocket
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
请求响应
http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("begin echo")
defer fmt.Println("end echo")
conn, _ := upgrader.Upgrade(w, r, nil)
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
return
}
if err = conn.WriteMessage(msgType, msg); err != nil {
return
}
}
})
完整源码
<input id="input" type="text" />
<button onclick="send()">Sendbutton>
<pre id="output">pre>
<script>
var input = document.getElementById("input");
var output = document.getElementById("output");
var socket = new WebSocket("ws://localhost:8090/echo");
socket.onopen = function () {
output.innerHTML += "Status: Connected\n";
};
socket.onmessage = function (e) {
output.innerHTML += "Server: " + e.data + "\n";
};
function send() {
socket.send(input.value);
input.value = "";
}
script>
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func main() {
http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
fmt.Println("begin echo")
defer fmt.Println("end echo")
conn, _ := upgrader.Upgrade(w, r, nil)
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
return
}
fmt.Printf("%s sent %d: %s\n", conn.RemoteAddr(), msgType, string(msg))
if err = conn.WriteMessage(msgType, msg); err != nil {
return
}
}
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "websockets.html")
})
http.ListenAndServe(":8090", nil)
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)