golang websocket 群聊
服务端代码
package main
import (
"fmt"
"net/http"
"sync"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type wsInfo struct {
Conn *websocket.Conn
Name string
}
var wsMap sync.Map
func main() {
http.HandleFunc("/im", func(w http.ResponseWriter, r *http.Request) {
conn, _ := upgrader.Upgrade(w, r, nil) // error ignored for sake of simplicity
remoteAddr := conn.RemoteAddr().String()
if _, ok := wsMap.Load(remoteAddr); !ok {
msgType, name, err := conn.ReadMessage()
if err != nil {
return
}
wsMap.Store(remoteAddr, wsInfo{Conn: conn, Name: string(name)})
conn.WriteMessage(msgType, []byte("您昵称:"+string(name)))
}
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
return
}
load, _ := wsMap.Load(remoteAddr)
res := fmt.Sprintf("%s:%s", load.(wsInfo).Name, string(msg))
wsMap.Range(func(key, value interface{}) bool {
if err = value.(wsInfo).Conn.WriteMessage(msgType, []byte(res)); err != nil {
return true
}
return true
})
}
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.ListenAndServe(":8080", nil)
}
客户端
<input id="input" type="text" placeholder="第一次输入昵称" />
<button onclick="send()">Send</button>
<pre id="output"></pre>
<script>
var input = document.getElementById("input");
var output = document.getElementById("output");
var socket = new WebSocket("ws://localhost:8080/im");
socket.onopen = function () {
output.innerHTML += "Status: Connected\n";
};
socket.onmessage = function (e) {
output.innerHTML += "Server: " + e.data + "\n";
};
function send() {
socket.send(input.value);
input.value = "";
}
</script>
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/16251311.html