I'm implementing chat with html5 web sockets in go lang and having errors both at client and server end.
Client Error:
WebSocket connectiont to 'ws://192.168.16.90:4000` failed: Invalid HTTP version string GET
Server Error:
continous looping of the following log message in the terminal,
connection closed received message: message sent:
Server Code:
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))
}
}
Client Code:
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);
};