packagemainimport("log""net/http""github.com/gorilla/websocket")varupgraderwebsocket.Upgrader=websocket.Upgrader{CheckOrigin:func(r*http.Request)bool{returntrue},}funcsocketHandler(whttp.ResponseWriter,r*http.Request){conn,err:=upgrader.Upgrade(w,r,nil)iferr!=nil{log.Fatalln("Error during connection upgration:",err)}deferconn.Close()for{messageType,message,err:=conn.ReadMessage()iferr!=nil{log.Println("Error during message reading:",err)break}log.Printf("Received:%s",message)err=conn.WriteMessage(messageType,message)iferr!=nil{log.Println("Error during message writing:",err)break}}}funcHome(whttp.ResponseWriter,r*http.Request){http.ServeFile(w,r,"index.html")}funcmain(){http.HandleFunc("/ws",socketHandler)http.HandleFunc("/",Home)err:=http.ListenAndServe(":8080",nil)iferr!=nil{log.Fatal(err)}}
packagemainimport("log""net/http""sync""github.com/gorilla/websocket")varconnections=make([]*websocket.Conn,0)varmusync.Mutex// Mutex to protect the connections slice
varupgraderwebsocket.Upgrader=websocket.Upgrader{CheckOrigin:func(r*http.Request)bool{returntrue},}funcsocketHandler(whttp.ResponseWriter,r*http.Request){conn,err:=upgrader.Upgrade(w,r,nil)iferr!=nil{log.Println("Error during connection upgrade:",err)return}mu.Lock()connections=append(connections,conn)mu.Unlock()deferfunc(){mu.Lock()fori,c:=rangeconnections{ifc==conn{connections=append(connections[:i],connections[i+1:]...)break}}mu.Unlock()conn.Close()log.Println("Client disconnected:",conn.RemoteAddr().String())}()log.Println("Client connected:",conn.RemoteAddr().String())for{clientInfo:=conn.RemoteAddr().String()+"\t"messageType,message,err:=conn.ReadMessage()iferr!=nil{ifwebsocket.IsCloseError(err,websocket.CloseNormalClosure,websocket.CloseGoingAway){log.Println("Connection closed by client:",conn.RemoteAddr().String())}else{log.Println("Error during message reading:",err)}break}ifmessageType==websocket.TextMessage{log.Printf("Received from %s message: %s",clientInfo,string(message))}elseifmessageType==websocket.BinaryMessage{log.Printf("Received binary message from %s",clientInfo)}mu.Lock()for_,client:=rangeconnections{ifclient!=conn{err:=client.WriteMessage(messageType,message)iferr!=nil{log.Println("Error during message writing:",err)}}}mu.Unlock()}}funcHome(whttp.ResponseWriter,r*http.Request){http.ServeFile(w,r,"index.html")}funcmain(){http.HandleFunc("/ws",socketHandler)http.HandleFunc("/",Home)err:=http.ListenAndServe(":8080",nil)iferr!=nil{log.Fatal(err)}}
funcsocketHandler(whttp.ResponseWriter,r*http.Request){conn,err:=upgrader.Upgrade(w,r,nil)iferr!=nil{log.Println("Error during connection upgrade:",err)return}mu.Lock()connections=append(connections,conn)mu.Unlock()deferfunc(){mu.Lock()fori,c:=rangeconnections{ifc==conn{connections=append(connections[:i],connections[i+1:]...)break}}mu.Unlock()conn.Close()log.Println("Client disconnected:",conn.RemoteAddr().String())}()log.Println("Client connected:",conn.RemoteAddr().String())for{clientInfo:=conn.RemoteAddr().String()+"\t"messageType,message,err:=conn.ReadMessage()iferr!=nil{ifwebsocket.IsCloseError(err,websocket.CloseNormalClosure,websocket.CloseGoingAway){log.Println("Connection closed by client:",conn.RemoteAddr().String())}else{log.Println("Error during message reading:",err)}break}ifmessageType==websocket.TextMessage{log.Printf("Received from %s message: %s",clientInfo,string(message))}elseifmessageType==websocket.BinaryMessage{log.Printf("Received binary message from %s",clientInfo)}mu.Lock()for_,client:=rangeconnections{ifclient!=conn{err:=client.WriteMessage(messageType,message)iferr!=nil{log.Println("Error during message writing:",err)}}}mu.Unlock()}}
接下来我们编写socketHandler函数,
http升级为websocket部分
这行我们实现对http的升级
1
2
3
4
5
conn,err:=upgrader.Upgrade(w,r,nil)iferr!=nil{log.Println("Error during connection upgrade:",err)return}
clientInfo:=conn.RemoteAddr().String()+"\t"messageType,message,err:=conn.ReadMessage()iferr!=nil{ifwebsocket.IsCloseError(err,websocket.CloseNormalClosure,websocket.CloseGoingAway){log.Println("Connection closed by client:",conn.RemoteAddr().String())}else{log.Println("Error during message reading:",err)}break}ifmessageType==websocket.TextMessage{log.Printf("Received from %s message: %s",clientInfo,string(message))}elseifmessageType==websocket.BinaryMessage{log.Printf("Received binary message from %s",clientInfo)}
mu.Lock()for_,client:=rangeconnections{ifclient!=conn{err:=client.WriteMessage(messageType,message)iferr!=nil{log.Println("Error during message writing:",err)}}}mu.Unlock()