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

浏览器收到的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条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料