douxie4583 2014-07-19 19:09
浏览 25
已采纳

Go服务器未听到远程请求

I've written a Go server that works perfectly as long as you send it requests from localhost (and addressed to localhost), but it doesn't work when you try to access it from a browser (from a different computer) or even just directed at the external IP address. I want to be able to access it as an external server, not just locally. Why can't it?

The (pared down) source code:

package main

import (
    "fmt"
    "net"
    "os"
)

func main() {
    // Listen for incoming connections.
    l, err := net.Listen("tcp", "localhost:2082")
    if err != nil {
        fmt.Println("Error listening:", err.Error())
        os.Exit(1)
    }
    // Close the listener when the application closes.
    defer l.Close()

    for {
        // Listen for an incoming connection.
        _, err := l.Accept()
        if err != nil {
            fmt.Println("Error accepting: ", err.Error())
            os.Exit(1)
        }
        fmt.Println("Incoming connection")
    }
}

When you curl localhost:2082, it says "Incoming connection".
When you curl mydomain.com:2082, it does nothing.

The port is forwarded. I'm sure of this because I ran a (node.js) web server from that port, and it worked fine. If it's related, I'm running on Ubuntu 12.04 on an Amazon EC2 instance.

I'd appreciate any help. Thanks!

  • 写回答

1条回答 默认 最新

  • dongpixi2648 2014-07-19 19:26
    关注

    One way to listen to any incoming IP (not just localhost, mapped by default to 127.0.0.1) would be:

    net.Listen("tcp", ":2082")
    

    You also have the function net/http/#ListenAndServe, which allows you to trigger listen on multiple specific ip if you want.

    go http.ListenAndServe("10.0.0.1:80", nil)
    http.ListenAndServe("10.0.0.2:80", nil) 
    

    A good example can be seen in "A Recap of Request Handling in Go".

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件