英文:
Websockets Read/Write
问题
你好!以下是你要翻译的内容:
我是一个Go/Websockets的新手。
我修改了这个可工作的示例,不再使用
io.Copy(ws,ws)
而是使用
msg := []byte{}
_, err := ws.Read(msg)
_, err = ws.Write(msg)
(为了简洁起见,省略了打印错误的部分)
对我来说,它看起来是一样的,但是它不起作用。它没有读取任何内容(尽管也没有返回错误)。在客户端(Chrome/FF)上,当尝试发送第二条消息时,我收到"WebSocket is already in CLOSING or CLOSED state"的错误。
总的来说,在Go语言中,对于WebSocket的读取消息 -> 做一些操作 -> 写入消息
的方法是什么?
英文:
Go/websockets noob here.
I've modified this working example in such way that instead of
io.Copy(ws,ws)
I am doing
msg := []byte{}
_, err := ws.Read(msg)
_, err = ws.Write(msg)
(printing errors omitted for brevity)
To me it looks the same, but it does not work. It does not read anything (though does not return error either). And on the client side (Chrome/FF) I get "WebSocket is already in CLOSING or CLOSED state" when trying to send second message.
In general, what is the approach for read msg -> do something -> write msg
for ws in golang?
答案1
得分: 3
在进行这个操作时,你需要分配一个实际的缓冲区大小来读取和写入字节。而且,它需要在一个循环内进行。
ws.Read() 不会为你分配一个缓冲区,它只会读取 len(msg)
,在你的例子中,它是0。
参考 io.Copy 的源码:
buf := make([]byte, 32*1024)
for {
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
英文:
When doing this, you read and write 0 bytes, you need to allocate an actual buffer size. And also, it needs to be within a loop.
ws.Read() will not allocate a buffer for you and will read only len(msg)
, In your example, it is 0.
Cf io.Copy sources:
buf := make([]byte, 32*1024)
for {
nr, er := src.Read(buf)
if nr > 0 {
nw, ew := dst.Write(buf[0:nr])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论