main.go
package main
import (
"fmt"
"net/http"
"time"
"golang.org/x/net/websocket"
)
type Connect struct {
wc *websocket.Conn
sc chan []byte
}
var H = make(map[*Connect]bool, 2)
func (c *Connect) writer() {
for msg := range c.sc {
fmt.Printf("%#v\n", c.sc)
c.wc.Write(msg)
}
}
func (c *Connect) reader() {
for range time.NewTicker(time.Second).C {
buf := make([]byte, 1500)
n, err := c.wc.Read(buf)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(buf[:n]))
if len(string(buf[:n])) < 1 {
continue
}
for conn := range H {
// fmt.Printf("%#v\n", conn)
conn.sc <- buf[:n]
}
}
}
func msg(wc *websocket.Conn) {
c := &Connect{
wc: wc,
sc: make(chan []byte),
}
// H = Hub{r: make(chan *Connect, 100)}
if c.wc != nil {
H[c] = true
}
go c.writer()
c.reader()
}
func main() {
http.Handle("/", http.FileServer(http.Dir("./")))
http.Handle("/msg", websocket.Handler(msg))
fmt.Println("start server at 8081")
http.ListenAndServe(":8081", nil)
}
index.html
<html>
<head>
<title>socket test</title>
</head>
<script>
const socket = new WebSocket(`ws://${window.location.host}/msg`);
socket.onmessage = e => {
document.getElementById("msg").innerHTML += e.data + "<br />";
}
function submit() {
let inputmsg = document.getElementById("name").value +"说:" +document.getElementById("input").value;
console.log(inputmsg)
socket.send(inputmsg)
}
</script>
<body>
<div> Name:<input type="text" id="name" value="小明" /> </div>
<div> Massage:<input type="text" id="input" /> <input type="submit" onclick="submit()"> </div>
Content:
<div id="msg"></div>
</body>
</html>
技术支持:
http://www.qiaihua.com