golang beego框架学习(十一)

AndyYang| 阅读:656 发表时间:2017-05-01 21:50:36 golang
摘要:本章主要讲解Go如何实现简易websocket通讯功能。

本章主要讲解Go如何实现简易websocket通讯功能。

server.go,源码:
package main

import (
	"fmt"
	"golang.org/x/net/websocket"
	"html/template"
	"log"
	"net/http"
)

const tpl = `<html>
<head></head>
<body>
    <script type="text/javascript">
        var sock = null;
        var wsuri = "ws://127.0.0.1:1234";

        window.onload = function() {

            console.log("onload");

            sock = new WebSocket(wsuri);

            sock.onopen = function() {
                console.log("connected to " + wsuri);
            }

            sock.onclose = function(e) {
                console.log("connection closed (" + e.code + ")");
            }

            sock.onmessage = function(e) {
                console.log("message received: " + e.data);
                document.getElementById('webyang_net').innerHTML = e.data;
            }
        };

        function send() {
            var msg = document.getElementById('message').value;
            sock.send(msg);
        };
    </script>
    <h1>WebSocket Echo Test</h1>
    <form>
        <p>
            Message: <input id="message" type="text" value="Hello, world!">
        </p>
    </form>
    <button onclick="send();">Send Message</button>
    <h2 id='webyang_net'></h2>
</body>
</html>`

func Echo(ws *websocket.Conn) {
	var err error

	for {
		var reply string

		if err = websocket.Message.Receive(ws, &reply); err != nil {
			fmt.Println("Can't receive")
			break
		}

		fmt.Println("Received back from client: " + reply)

		msg := "Received:  " + reply
		fmt.Println("Sending to client: " + msg)

		if err = websocket.Message.Send(ws, msg); err != nil {
			fmt.Println("Can't send")
			break
		}
	}
}

func myHandler(w http.ResponseWriter, r *http.Request) {
	t := template.New("tpl")
	content, _ := t.Parse(tpl)
	content.Execute(w, nil)
}

func main() {
	http.Handle("/", websocket.Handler(Echo))
	http.Handle("/send", http.HandlerFunc(myHandler))

	if err := http.ListenAndServe("localhost:1234", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

命令行下执行:go run server.go
浏览器访问:http://localhost:1234/send
ie浏览器不支持websocket,所以用google或firefox测试。

github:https://github.com/yangsir/beego_study

本文为AndyYang原创,转载请注明出处!
如果您觉得好,可以打赏作者:
如果您觉得累了,是否想看点美女养养眼:猛戳>>若兰网
如果您觉得皮了,是否想来点神吐槽:猛戳>>iPhone查询中

已有0条评论

昵称:
邮箱:

  • 最新评论

iPhone查询中 - bbs.ipcxz.com 若兰网 - www.rolan.wang iPhone查询中 - bbs.ipcxz.com
反馈
微信订阅号