parent
af09f96078
commit
1db1a665ec
@ -0,0 +1,5 @@
|
||||
module demo/websocket
|
||||
|
||||
go 1.12
|
||||
|
||||
require github.com/gorilla/websocket v1.5.0
|
||||
@ -0,0 +1,2 @@
|
||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
@ -0,0 +1,44 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var upgrader = websocket.Upgrader{}
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "index.html")
|
||||
})
|
||||
fs := http.FileServer(http.Dir("static/"))
|
||||
http.Handle("/static/", http.StripPrefix("/static/", fs))
|
||||
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
|
||||
var conn, _ = upgrader.Upgrade(w, r, nil)
|
||||
go func(conn *websocket.Conn) {
|
||||
for {
|
||||
mType, msg, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
println("close with error")
|
||||
println(string(err.Error()))
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
println((string(msg)))
|
||||
switch mType {
|
||||
case 1:
|
||||
var sendmsg []byte = []byte("hi,I'm Go")
|
||||
conn.WriteMessage(mType, sendmsg)
|
||||
case 8:
|
||||
fmt.Println("client close")
|
||||
default:
|
||||
fmt.Println("type::" + string(rune(mType)))
|
||||
}
|
||||
|
||||
}
|
||||
}(conn)
|
||||
})
|
||||
println("serve start")
|
||||
http.ListenAndServe(":3000", nil)
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head></head>
|
||||
|
||||
<body>
|
||||
<div>Hello, World!</div>
|
||||
<script>
|
||||
var ws = new WebSocket("ws://localhost:3000/ws")
|
||||
ws.onopen = () => {
|
||||
console.log("open::")
|
||||
ws.send("hi,I'm chrome")
|
||||
ws.close()
|
||||
}
|
||||
ws.onmessage = (e) => {
|
||||
console.log("receive message::\n", e.data)
|
||||
}
|
||||
ws.close = () => {
|
||||
console.log("close::\n")
|
||||
}
|
||||
ws.onerror = (e) => {
|
||||
console.log("error::\n", e)
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@ -0,0 +1 @@
|
||||
second page
|
||||
Loading…
Reference in new issue