I have been trying to push changes done on server side using websockets in Golang.
I have achived what i wanted by this code
Server side code:
package main
import (
"golang.org/x/net/websocket"
"fmt"
"net/http"
"os"
"bufio"
)
type chat struct {
message string
}
func (ms *chat) Echo(ws *websocket.Conn) {
var reply string
for {
if reply != ms.message {
websocket.Message.Send(ws, ms.message)
}
websocket.Message.Receive(ws, reply)
}
}
func NewMessage(s *string){
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("Enter text: ")
*s, _ = reader.ReadString('
')
}
}
func main() {
myString := chat{"Welcome"}
go NewMessage(&myString.message)
http.Handle("/", websocket.Handler(myString.Echo))
http.ListenAndServe(":1234", nil)
}
Client side code:
<html>
<body>
<script type="text/javascript">
var exampleSocket = new WebSocket("ws://127.0.0.1:1234");
exampleSocket.onopen = function (event) {
console.log("connected");
};
exampleSocket.onmessage = function (event) {
console.log(event.data);
exampleSocket.send(event.data)
document.getElementById("p1").innerHTML = event.data;
}
</script>
<h1>WebSockets</h1>
<form>
<p id="p1" value="Hello, world!"/>
</form>
The problem with above code is repeatedly sending ms.message as if reply != ms.message
does not work. Simply var reply string
value is not being changed by websocket.Message.Receive(ws, reply)
.
I have tried passing reply
as a pointer but it does not update value on the client side dynamically.
Here is how server side would look like after the change:
package main
import (
"golang.org/x/net/websocket"
"fmt"
"net/http"
"os"
"bufio"
)
type chat struct {
message string
}
func (ms *chat) Echo(ws *websocket.Conn) {
var reply string
for {
if reply != ms.message {
websocket.Message.Send(ws, ms.message)
}
websocket.Message.Receive(ws, &reply)
}
}
func NewMessage(s *string){
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("Enter text: ")
*s, _ = reader.ReadString('
')
}
}
func main() {
myString := chat{"Welcome"}
go NewMessage(&myString.message)
http.Handle("/", websocket.Handler(myString.Echo))
http.ListenAndServe(":1234", nil)
}
This code does not fit my expectations.
Is it possible to dynamically update string on clients side without sending value multiple times as it is being done in the example number 1?