Node.js WebSocket客户端监听Golang WebSocket服务器实现问题求助
Alright, let's get your Golang WebSocket server sending messages and your Node.js client receiving them smoothly. First, let's fix up your existing Golang code (you had a small syntax issue) and add the message-sending logic, then build the matching Node.js client.
Golang WebSocket Server: Complete & Fixed Implementation
Your original code was missing a closing curly brace in the NewUpgrader() function, which would prevent compilation. Here's the full working server with logic to send periodic messages to connected clients:
package main import ( "log" "net/http" "time" "github.com/gorilla/websocket" ) type WebsocketHandler struct{} func NewUpgrader() *websocket.Upgrader { return &websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { // Allow all origins for development; replace with your client domain in production! return true }, } } func (s WebsocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { upgrader := NewUpgrader() ws, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Errorf("websocket: failed to upgrade connection: %v", err) return } defer ws.Close() // Ensure connection is cleaned up when handler exits log.Println("New client connected successfully") // Example: Send a message to the client every 3 seconds messageTicker := time.NewTicker(3 * time.Second) defer messageTicker.Stop() for { select { case <-messageTicker.C: // Prepare and send your message outgoingMsg := "Hello from Golang WebSocket server!" err := ws.WriteMessage(websocket.TextMessage, []byte(outgoingMsg)) if err != nil { log.Errorf("websocket: failed to send message: %v", err) return } log.Printf("Sent message: %s", outgoingMsg) case <-ws.CloseHandler()(): log.Println("Client disconnected") return } } } func main() { http.Handle("/ws", WebsocketHandler{}) log.Println("Server running on http://localhost:8080/ws") log.Fatal(http.ListenAndServe(":8080", nil)) }
Key Notes for the Server:
- Critical Syntax Fix: We added the missing closing brace in
NewUpgrader()— this was preventing your code from compiling. - Connection Cleanup: The
defer ws.Close()ensures the WebSocket connection is properly closed when the handler exits. - Message Sending: We used a ticker to demonstrate periodic messages, but you can replace this with your own logic (e.g., triggering messages based on events, API calls, etc.).
- Security Note: The
CheckOriginreturnstruefor development convenience. In production, replace this with a check that validates the client's origin matches your allowed domain(s) to prevent CSRF attacks.
Node.js WebSocket Client: Receive Messages
We'll use the widely-used ws package for the client. First install it via npm:
npm install ws
Then create your client script:
const WebSocket = require('ws'); // Connect to your Golang server's WebSocket endpoint const client = new WebSocket('ws://localhost:8080/ws'); // Handle successful connection client.on('open', () => { console.log('Connected to Golang WebSocket server!'); }); // Listen for incoming messages from the server client.on('message', (message) => { console.log(`Received from server: ${message.toString()}`); }); // Handle connection errors client.on('error', (error) => { console.error('WebSocket connection error:', error); }); // Handle connection closure client.on('close', () => { console.log('Disconnected from the server'); });
Troubleshooting Common Issues
If you're having trouble getting messages to flow between server and client:
- Check Compilation: Make sure your Golang code compiles without errors (the missing brace was the main one, but double-check imports and syntax).
- Verify Connection: Confirm the Node.js client is using the correct URL (
ws://localhost:8080/wsmust match the server's route). - Port Access: Ensure port 8080 isn't blocked by a firewall or used by another application.
- Message Type Consistency: Both server and client should use the same message type (we used text messages here; binary messages require different handling).
- Logging: Use the log statements in both server and client to confirm connections are established and messages are being sent/received.
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

