博文链接:https://blog.csdn.net/weixin_43757001/article/details/90116651
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
)
var (
upgrader = websocket.Upgrader{}
)
func main() {
e := echo.New()
// e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.Static("/", "./")
e.GET("/hello", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.GET("/echo", getEcho)
e.POST("/echo", postEcho)
e.GET("/list", func(c echo.Context) error {
type Camera struct {
ID string `json:"id"`
Name string `json:"name"`
Num int `json:"num"`
}
type List struct {
List []Camera `json:"list"`
}
list := new(List)
c1 := Camera{"001", "camera1", 10}
c2 := Camera{"002", "camera2", 20}
c3 := Camera{"003", "camera3", 30}
list.List = append(list.List, c1)
list.List = append(list.List, c2)
list.List = append(list.List, c3)
return c.JSON(http.StatusCreated, list)
})
e.GET("/ws", wsEcho)
e.Logger.Fatal(e.Start(":8800"))
}
func wsEcho(c echo.Context) error {
ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)
if err != nil {
return err
}
defer ws.Close()
// Write
err = ws.WriteMessage(websocket.TextMessage, []byte("Hello, Client!"))
if err != nil {
c.Logger().Error(err)
}
for {
// Read
_, msg, err := ws.ReadMessage()
if err != nil {
c.Logger().Error(err)
}
fmt.Printf("wsEcho:%s\n", msg)
// Write
err = ws.WriteMessage(websocket.TextMessage, []byte(msg))
if err != nil {
c.Logger().Error(err)
}
}
}
// get url /echo?str="xxxxx"
func getEcho(c echo.Context) error {
str := c.QueryParam("str")
return c.String(http.StatusOK, str)
}
// post url /echo with body form value "str"
func postEcho(c echo.Context) error {
str := c.FormValue("str")
return c.String(http.StatusOK, str)
}
由以上可以看出,服务器端储存着json数据
{
"list":[
{"id":"001","name":"camera1","num":10},
{"id":"002","name":"camera2","num":20},
{"id":"003","name":"camera3","num":30}
]
}
<body>
<div>
<table id="customers">
<tr id="one">
<th>idth>
<th>nameth>
<th>numth>
tr>
<tr>
<td>td>
<td>td>
<td>td>
tr>
<tr class="alt">
<td>td>
<td>td>
<td>td>
tr>
<tr>
<td>td>
<td>td>
<td>td>
tr>
table>
div>
body>
<style type="text/css">
#customers {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
width: 100%;
border-collapse: collapse;
}
#customers td,
#customers th {
font-size: 1em;
border: 1px solid #98bf21;
padding: 3px 7px 2px 7px;
}
#customers th {
font-size: 1.1em;
text-align: left;
padding-top: 5px;
padding-bottom: 4px;
background-color: #A7C942;
color: #ffffff;
}
#customers tr.alt td {
color: #000000;
background-color: #EAF2D3;
}
style>
<script type="text/javascript">
var list = {}; //list对象储存各行id,name,num的值
//遍历displayList数组,将数组中的数据传回页面,填充table表格各行id,name,num的值
function DisplayList(displayList) {
var customers = document.getElementById("customers");
displayList.forEach(function (obj, i) {
customers.rows[i + 1].cells[0].innerHTML = obj.id;
customers.rows[i + 1].cells[1].innerHTML = obj.name;
customers.rows[i + 1].cells[2].innerHTML = obj.num;
})
}
window.onload = function () {
//Ajax获取后台id,name,num的值
var xmlhttp;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp = new XMLHttpRequest();
console.log(xmlhttp);
}
else {
// IE6, IE5 浏览器执行代码
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
console.log('xmlreadyState:' + xmlhttp.readyState);
console.log('xmlstatus:' + xmlhttp.status);
if (xmlhttp.readyState == 4 && xmlhttp.status == 201) {
//初始化table内容
//将服务器端json数据转成js对象,传回前端页面
var json = xmlhttp.responseText;
console.log(json);
var jsonToJs = JSON.parse(json);
console.log(jsonToJs);
//填充list对象的内容,准备初始化table内容,注意此处list对象的索引为jsonToJs.list[i]的id值,而非常规的从0开始的索引号
for (var i = 0; i < jsonToJs.list.length; i++) {
list[jsonToJs.list[i].id] = jsonToJs.list[i];
console.log(jsonToJs.list[i]);
}
console.log(list);
DisplayList(jsonToJs.list);//初始化table内容
//建立websocket连接
var ws = new WebSocket("ws://127.0.0.1:8800/ws");
var interval_num;
function sortDisplayList(a, b) {
return a.num - b.num;
}
ws.onopen = function () {
console.log("open");
function rnd(n, m) {
var random = Math.floor(Math.random() * (m - n + 1) + n);
return random;
}
interval_num = setInterval(function () {
var ids = {};
ids["001"] = rnd(1, 50);
ws.send(JSON.stringify(ids));
}, 2000);
};
ws.onmessage = function (evt) {
if (evt.data.indexOf("Hello") != -1) {
return;
}
var ids = JSON.parse(evt.data);
list["001"].num = ids["001"];
var displayList = new Array();
for (id in list) {
displayList.push(list[id]);
}
displayList.sort(sortDisplayList);
DisplayList(displayList);
};
ws.onclose = function (evt) {
console.log("WebSocketClosed!");
};
ws.onerror = function (evt) {
console.log("WebSocketError!");
};
}
}
xmlhttp.open("GET", "http://127.0.0.1:8800/list", true);
xmlhttp.send();
}
</script>