Websockets

Websockets,第1张

安装gorilla/websocket

go get -u github.com/gorilla/websocket

创建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)
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/990571.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存