dqhdpppm02183 2013-05-12 12:55
浏览 1020
已采纳

浏览器收到的Websocket输出抱怨“标头值中的UTF-8序列无效”

When I load the page in my browser, the page gets served correctly. When the javascript executes, Chrome's console output says:

Invalid UTF-8 sequence in header value 

I have searched for that string, and am unable to find any mention of it for golang.

How do I go about telling golang not to write unicode characters to web sockets?

I assume that this is the cause of the problem, as the "Network" tab only reveals an empty request and response for this.


CCSSE:

main.go:

package main

import (
  "fmt"
  "net/http"
  "log"
  "code.google.com/p/go.net/websocket"
  //"github.com/garyburd/go-websocket/websocket"
)

const listenAddress = "localhost:9999"

func wsHandler(webSck *websocket.Conn) {
  fmt.Fprint(webSck, "Rpy")
  fmt.Println("Sent \"Rpy\" to web socket", webSck)
  //more code here
}

func main() {
  http.Handle("/", http.FileServer(http.Dir("./static")))
  http.Handle("/ws", websocket.Handler(wsHandler))
  err := http.ListenAndServe(listenAddress, nil)
  if err != nil {
    log.Fatal(err)
  }
}

static/main.js

var socket = new WebSocket("ws://localhost:9999/ws");
socket.onopen = function() {
  socket.onmessage = function(m) {
    console.log("Received: " + m);
  };
  socket.send("Req
");
};

EDIT:

As suggested by @Intermernet, I have set the Sec-WebSocket-Protocol header. To no avail, still getting Invalid UTF-8 sequence in header value.

Note also that the reason I need to do webSck.Config().Header = make(http.Header) is that it is nil - confirmed by the log statement on webSck.Config(). Tack on to this another question - why do I have to do this; is there an intialisation step that I have missed somewhere?

func wsHandler(webSck *websocket.Conn) {
  webSck.Config().Header = make(http.Header)
  webSck.Config().Header.Add("Sec-WebSocket-Protocol", "chat")
  fmt.Printf("ws.Config()  %#v
", webSck.Config())
  var buf []byte;
  buf = []byte("Rpy")
  _, err := webSck.Write(buf)
  if err != nil {
    fmt.Println("Error:", err)
  } else {
    fmt.Printf("Sent \"Rpy\" to web socket  %#v
", webSck)
  }
}
  • 写回答

2条回答 默认 最新

  • dsepcxw181184853 2013-05-13 19:01
    关注

    Can this issue be related to recent change in code.google.com/p/go.net/websocket ?

    https://code.google.com/p/go/source/detail?r=1e65ca1b2499c473ec267ca1d6759b3dc920a599&repo=net

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题