我在go lang中实现与html5网络套接字的聊天,并在客户端和服务器端都有错误。
客户端错误:
WebSocket连接到' ws://192.168.16.90:4000`失败:无效的HTTP版本字符串GET
服务器错误:
在终端中连续循环以下日志消息,
连接已关闭\ n已收到消息:\ n已发送消息:\ n
服务器代码:
func (s *Service) InitializeService() {
listener, err := net.Listen("tcp", ":4000")
if err != nil {
log.Fatal(err)
}
log.Println("Chat server started to listen on port ", listener.Addr())
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal(err)
}
fmt.Println("A new connection accepted.")
go listenConnection(conn)
}
}
func listenConnection(conn net.Conn) {
for {
buffer := make([]byte, 1400)
dataSize, err := conn.Read(buffer)
if err != nil {
fmt.Println("connection closed")
}
data := buffer[:dataSize]
fmt.Println("received message: ", string(data))
_, err = conn.Write(data)
if err != nil {
log.Fatalln(err)
}
fmt.Println("message sent: ", string(data))
}
}
客户代码:
var connection = new WebSocket("ws://192.168.16.90:4000");
connection.onopen = function() {
console.log("onopen");
connection.send("Ping");
};
connection.onerror = function(error) {
console.log("WebSocket Error", error);
};
connection.onmessage = function(e) {
console.log("Server: ", e.data);
};