完整代码:https://github.com/diguacheng/webchat
扩展包 gorilla/websocket的几个重要函数
- 协议升级 ,1)先初始化upgrader,再调用其upgrade方法将http协议升级为websicket协议。2)也可以直接使用upgrade函数 进行协议升级
type Upgrader struct {
HandshakeTimeout time.Duration
ReadBufferSize, WriteBufferSize int
WriteBufferPool BufferPool
Subprotocols []string
Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
CheckOrigin func(r *http.Request) bool
EnableCompression bool
}
func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
u := Upgrader{
ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
// don't return errors to maintain backwards compatibility
}
u.CheckOrigin = func(r *http.Request) bool {
// allow all connections by default
return true
}
return u.Upgrade(w, r, responseHeader)
}
func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
u := Upgrader{
ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
// don't return errors to maintain backwards compatibility
}
u.CheckOrigin = func(r *http.Request) bool {
// allow all connections by default
return true
}
return u.Upgrade(w, r, responseHeader)
}
-
服务端发送数据
使用
func (c *Conn) WriteMessage(messageType int, data []byte) error
方法。或者使用
func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error)
方法获得writer,再调用func (w *messageWriter) Write(p []byte) (int, error)
将数据写入。 -
服务端接受数据
使用
func (c *Conn) ReadMessage() (messageType int, p []byte, err error)
方法。
其他函数方法可参考文档
项目实战 web实时聊天室
项目的架构如图所示:
// Client is a middleman between the websocket connection and the hub.
type Client struct {
// The websocket connection.
conn *websocket.Conn
// Buffered channel of outbound messages.
send chan []byte
Data *Data
}
// Data 定义传输的数据,
type Data struct {
IP string `json:"ip"` // 本地ip
Type string `json:"type"` // 类型
User string `json:"user"` // 接受信息的用户名
Form string `json:"from"` // 发送信息的用户名
FormIP string `json:"FromIp"`// 发送信息的IP
Content string `json:"content"` // 信息的内容。
}
// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
// Registered clients. // 一个client代表一个user
clients map[*Client]bool
// Inbound messages from the clients.
broadcast chan []byte
// Register requests from the clients.
register chan *Client
// Unregister requests from clients.
unregister chan *Client
}
hub.go
package main
// Hub maintains the set of active clients and broadcasts messages to the
// clients.
type Hub struct {
// Registered clients.
clients map[*Client]bool
// Inbound messages from the clients.
broadcast chan []byte
// Register requests from the clients.
register chan *Client
// Unregister requests from clients.
unregister chan *Client
}
func newHub() *Hub {
return