我一直在尝试使用Golang中的websockets在服务器端推送更改。
我已经通过此代码获得了我想要的东西
服务器端代码:
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('\n')
}
}
func main() {
myString := chat{"Welcome"}
go NewMessage(&myString.message)
http.Handle("/", websocket.Handler(myString.Echo))
http.ListenAndServe(":1234", nil)
}
客户端代码:
<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>
以上代码的问题是重复发送ms.message,因为if reply != ms.message
不起作用。 var reply string
只是websocket.Message.Receive(ws, reply)
值不会改变reply
值。
我尝试将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('\n')
}
}
func main() {
myString := chat{"Welcome"}
go NewMessage(&myString.message)
http.Handle("/", websocket.Handler(myString.Echo))
http.ListenAndServe(":1234", nil)
}
作为指针传递,但它不会动态更新客户端的值。
以下是更改后服务器端的外观:
selected
此代码不符合我的期望。
是否可以在客户端动态更新字符串而不像在示例1中那样多次发送值?
答案 0 :(得分:1)
只需将websocket.Message.Receive
放入if语句即可解决问题。
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('\n')
}
}
func main() {
myString := chat{"Welcome"}
go NewMessage(&myString.message)
http.Handle("/", websocket.Handler(myString.Echo))
http.ListenAndServe(":1234", nil)
}