加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
main.go 2.83 KB
一键复制 编辑 原始数据 按行查看 历史
unknown 提交于 2020-09-20 13:20 . v0.0.0.0.1
package main
import (
"github.com/gorilla/websocket"
"log"
"net/http"
)
import "github.com/gin-gonic/gin"
var upgrader = websocket.Upgrader{} // use default options
func readMess(c *websocket.Conn,key string) {
defer c.Close()
for{
// mt ==== 1
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
log.Printf("recv: %s", message)
//err = c.WriteMessage(mt, message)
globalRQue <- newMsg(key,string(message))
}
}
func WriteMess(){
for {
select {
case dat:= <- globalWQue:
playerList[dat.key].WriteMessage(1,[]byte(dat.data))
default:
}
}
}
func main() {
go WriteMess()
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.Data(http.StatusOK,"text/html; charset = utf-8",[]byte(homeTemplate))
})
r.GET("/wsconn/:key", func(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
key := c.Param("key")
playerList[key] = conn
go readMess(conn,key)
})
r.Run(":8000")
}
var homeTemplate = `
<!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.textContent = message;
output.appendChild(d);
};
document.getElementById("open").onclick = function(evt) {
if (ws) {
return false;
}
ws = new WebSocket("ws://localhost:8000/echo");
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>
<p><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>
`
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化