源代码
server.go
package main
import (
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
)
var upGrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func index(c *gin.Context) {
c.HTML(http.StatusOK, "websocket.html", nil)
}
func ping(c *gin.Context) {
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
defer ws.Close()
for {
mt, message, err := ws.ReadMessage()
if err != nil {
break
}
err = ws.WriteMessage(mt, message)
if err != nil {
break
}
}
}
func main() {
r := gin.Default()
r.LoadHTMLGlob("6-网络编程/src/*.html")
r.GET("/", index)
r.GET("/ws", ping)
r.Run("localhost:8000")
}
websocket.html
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<form action="" onsubmit="sendMessage(event)">
<input type="text" id="messageText" autocomplete="off"/>
<button>Send</button>
</form>
<ul id='messages'>
</ul>
<script>
var websocket = new WebSocket("ws://localhost:8000/ws");
websocket.onmessage = function (event) {
var messages = document.getElementById('messages')
var message = document.createElement('li')
var content = document.createTextNode(event.data)
message.appendChild(content)
messages.appendChild(message)
};
function sendMessage(event) {
var input = document.getElementById("messageText")
websocket.send(input.value)
input.value = ''
event.preventDefault()
}
</script>
</body>
</html>
|