drgd73844 2014-09-03 09:29
浏览 13
已采纳

使用Golang构建服务器,但客户端存在问题

This is my code:

package main

import (
        "fmt"
        "net"
        "net/http"
        "os"
)

const RECV_BUF_LEN = 1024

func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "Test")
}

func main() {
        http.HandleFunc("/", handler)
        s := &http.Server{Addr: ":8080", Handler: nil}
        listener, err := net.Listen("tcp", s.Addr)
        if err != nil {
                fmt.Println("Error: ", err.Error())
                fmt.Println("Close Server")
                os.Exit(1)
        }

        for {
                conn, err := l.Accept()
                if err != nil {
                        fmt.Println("Error: ", err.Error())
                        continue
                }
                go ClientLogic(conn)
        }
}

func ClientLogic(conn net.Conn) {
        fmt.Println("Connect Successful")
        conn.Close()
}

I know I can use following code to build a server but I want do some stuffs, such as printing some datas.

http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)

When the code run, the server-side can print "Connect Successful" successfully.

However, the it doesn't display anything in client-side.

In other words, the client's browser display anything and keep loading but the server-side can display the message about connecting successfully.

PS: The code refer to http://lolikitty.pixnet.net/blog/post/148420590 and the golang's source code ( http://golang.org/src/pkg/net/http/server.go?s=50405:50451#L1684 )

  • 写回答

3条回答 默认 最新

  • dousong2967 2014-09-03 10:55
    关注

    You should use the handler or the accept, but if you use the accept this will be handled the new connection and you are ignoring the handler. You are going to a lower abstraction level of the http connection.

    This piece of code work as you expect:

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func handler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "Test")
        fmt.Println("Connect Successful")
    }
    
    func main() {
        http.HandleFunc("/", handler)
        http.ListenAndServe(":8080", nil)
    }
    

    When you call to ListenAndServe, he make the correct Accept so you dont need to worry about.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏