'Using websocket for notifying frontend
There is backend using golang,frontend - JS. The task is to get updates on frontend (JS) from backend.
back code (Go):
func ini_WS(wsChan chan string) websocket.Upgrader { // invoke from main
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
var flag int64
go http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if atomic.CompareAndSwapInt64(&flag, 0, 1) {
go func() {
for data := range wsChan {
ws.WriteMessage(websocket.TextMessage, []byte(data))
fmt.Println("data sent")
}
}()
}
}))
return upgrader
}
During work of the app put data to the channel wsChan. And it works till refresh the web page. As soon as I refresh the page frontend doe not get messages (although according the debugger backend send them). It may be supposed to be done in another way. Please tell me how to realize this task in he correct way
front (JS)
conn = new WebSocket("ws://localhost:8080");
conn.onmessage = function (event) {
// ........
};
Solution 1:[1]
solution: you need to close the previous one before creating a new connection
var wsconn *websocket.Conn
var flag int64
go http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var err error
if wsconn != nil {
wsconn.Close()
}
wsconn, err = upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// .....
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ????? ??????? |
