ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 推荐库 ``` https://godoc.org/github.com/gorilla/websocket https://godoc.org/nhooyr.io/websocket ``` ## 语法 ### Func ``` func Origin(config *Config, req *http.Request) (*url.URL, error) ``` ### Type ``` type Addr func (addr *Addr) Network() string type Codec func (cd Codec) Receive(ws *Conn, v interface{}) (err error) func (cd Codec) Send(ws *Conn, v interface{}) (err error) type Config func NewConfig(server, origin string) (config *Config, err error) type Conn func Dial(url_, protocol, origin string) (ws *Conn, err error) func DialConfig(config *Config) (ws *Conn, err error) func NewClient(config *Config, rwc io.ReadWriteCloser) (ws *Conn, err error) func (ws *Conn) Close() error func (ws *Conn) Config() *Config func (ws *Conn) IsClientConn() bool func (ws *Conn) IsServerConn() bool func (ws *Conn) LocalAddr() net.Addr func (ws *Conn) Read(msg []byte) (n int, err error) func (ws *Conn) RemoteAddr() net.Addr func (ws *Conn) Request() *http.Request func (ws *Conn) SetDeadline(t time.Time) error func (ws *Conn) SetReadDeadline(t time.Time) error func (ws *Conn) SetWriteDeadline(t time.Time) error func (ws *Conn) Write(msg []byte) (n int, err error) type Handler func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) type Server func (s Server) ServeHTTP(w http.ResponseWriter, req *http.Request) ``` ## 示例 <details> <summary>main.go</summary> ``` package main import ( "golang.org/x/net/websocket" "fmt" "log" "net/http" ) func Echo(ws *websocket.Conn) { var err error for { var reply string if err = websocket.Message.Receive(ws, &reply); err != nil { fmt.Println("Can't receive") break } fmt.Println("Received back from client: " + reply) msg := "Received: " + reply fmt.Println("Sending to client: " + msg) if err = websocket.Message.Send(ws, msg); err != nil { fmt.Println("Can't send") break } } } func main() { http.Handle("/", websocket.Handler(Echo)) if err := http.ListenAndServe(":1234", nil); err != nil { log.Fatal("ListenAndServe:", err) } } ``` </details> <br />