Golang实现GRPC时遭遇连接拒绝错误的技术求助
Let’s walk through the common reasons you’re hitting this error and how to fix them step by step:
1. Your gRPC Server Isn’t Running (or Listening on the Right Port)
First things first—make sure your gRPC server is actually up and running, and that it’s listening on port 9001.
- Double-check your server code’s listen address: it should look like this:
If the port here is different (e.g.,lis, err := net.Listen("tcp", ":9001") if err != nil { log.Fatalf("failed to listen: %v", err) }:8080), that’s why your client can’t connect. - Verify the port is being used by your server:
- On Linux/macOS: Run
lsof -i :9001—you should see your server process listed. - On Windows: Run
netstat -ano | findstr :9001and check if there’s a process ID associated with the port.
- On Linux/macOS: Run
2. Client Code Wastes the addr Parameter (Hardcodes the Port)
Looking at your InitEventServiceClient function: you accept an addr parameter but never use it! You’re hardcoding localhost:9001 instead. That’s a problem if your server is on a different machine or uses a different port.
Fix this by using the passed-in address (and update the parameter type to a string, since ports are part of a network address string):
func InitEventServiceClient(addr string) (msc EventServiceClient, err error) { conn, err := grpc.Dial(addr, grpc.WithInsecure()) if err != nil { return } client := proto.NewEventServiceClient(conn) msc = EventServiceClient{ Conn: conn, Client: client, } return }
Then call it with the correct address, e.g., InitEventServiceClient("localhost:9001").
3. Firewall or Network Blocking the Connection
- If your server is on another machine, ensure the firewall on that machine allows incoming traffic on port 9001.
- On your local machine, check if a firewall (like Windows Firewall or iptables on Linux) is blocking outgoing connections to port 9001.
- Try replacing
localhostwith127.0.0.1in the client address—rarely, localhost resolution can have issues, and using the direct loopback IP might help.
4. Server Has Misconfigured gRPC Setup
Make sure your server is properly registering the service and starting the gRPC server:
s := grpc.NewServer() proto.RegisterEventServiceServer(s, &yourEventServiceImplementation{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) }
Also, check if your server is throwing any startup errors (like permission issues if you’re using a port below 1024 without root/admin rights).
Start with the first two checks—they’re the most likely culprits here!
内容的提问来源于stack exchange,提问作者Gourav Jondhale

