go websocket
时间: 2023-09-23 11:02:36 浏览: 96
go-websocket
WebSockets are a protocol that provides a bi-directional, full-duplex communication channel over a single TCP connection. They enable real-time, low-latency communication between a client (usually a web browser) and a server.
To use WebSockets in a Go application, you can use the `gorilla/websocket` package. Here's an example of how to set up a WebSocket server:
```
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func main() {
http.HandleFunc("/ws", handleWebSocket)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handleWebSocket(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("error upgrading to WebSocket:", err)
return
}
defer conn.Close()
for {
// Read message from client
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("error reading message:", err)
break
}
// Echo message back to client
err = conn.WriteMessage(websocket.TextMessage, message)
if err != nil {
log.Println("error writing message:", err)
break
}
}
}
```
In this example, we first set up an `upgrader` that will upgrade an HTTP connection to a WebSocket connection. We then define a `handleWebSocket` function that will handle WebSocket connections. Inside this function, we upgrade the connection using the `upgrader`, and then enter a loop to read messages from the client and echo them back.
To connect to this WebSocket server from a web browser, you can use JavaScript and the `WebSocket` API:
```
const ws = new WebSocket("ws://localhost:8080/ws");
ws.addEventListener("open", () => {
console.log("Connected to WebSocket server");
});
ws.addEventListener("message", (event) => {
console.log("Received message from server:", event.data);
});
ws.addEventListener("close", () => {
console.log("Disconnected from WebSocket server");
});
ws.send("Hello, server!");
```
In this example, we create a new `WebSocket` object and connect to the server at `ws://localhost:8080/ws`. We then set up event listeners for the `open`, `message`, and `close` events. When the connection is opened, we log a message to the console. When a message is received from the server, we log it to the console. When the connection is closed, we log a message to the console. Finally, we send a message to the server using the `send` method.
阅读全文