// Create a WebSocket connection to the server conn, err := websocket.Dial("ws://example.com/ws", "", "http://example.com") if err != nil { log.Fatal(err) } defer conn.Close() // Send a message to the server if err := websocket.Message.Send(conn, []byte("Hello, server")); err != nil { log.Fatal(err) } // Receive a message from the server var msg []byte if err := websocket.Message.Receive(conn, &msg); err != nil { log.Fatal(err) } fmt.Println(string(msg))
// Create a WebSocket server server := &websocket.Server{Handler: websocket.Handler(echoHandler)} // Listen for WebSocket connections http.Handle("/echo", server) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) } // Handle incoming WebSocket messages func echoHandler(conn *websocket.Conn) { for { var msg []byte err := websocket.Message.Receive(conn, &msg) if err != nil { break } err = websocket.Message.Send(conn, msg) if err != nil { break } } }In this example, we create a WebSocket server that echoes back any messages sent to it. We use the Handler field of a websocket.Server to specify how incoming connections should be handled, and then listen for incoming connections with http.ListenAndServe. The echoHandler function reads incoming messages from the client, sends them back to the client, and breaks out of the loop if there is an error reading or sending a message.