使用 go channel 的 go echo 服务器,但没有来自服务器的回复

我正在尝试使用 go channel 和 goroutine 来编写一个回显服务器,但是没有来自服务器的回复。下面的服务器监听 9090 端口,并创建一个通道ch来接收连接接受,然后它传递handleClient给处理连接细节。下面的代码有错吗?下时它没有错误go build。


package main


import (

    "fmt"

    "net"

)


const (

    CONN_HOST = "localhost"

    CONN_PORT = "9090"

    CONN_TYPE = "tcp"

)


func main() {

    listen, err := net.Listen(CONN_TYPE, CONN_HOST + ":" + CONN_PORT)

    if err != nil {

        fmt.Println("Error listening: ", err.Error())

        return

    }


    ch := make(chan net.Conn)

    go func() {

        for {

            conn, err := listen.Accept()

            if err != nil {

                fmt.Println("Error Accept: ", err.Error())

                return

            }

            ch <- conn

        }

    }()

    go handleClient(ch)

}


func handleClient(connChan <-chan net.Conn) {

    var tcpConn net.Conn

    // fmt.Println("Accepted new client: ", connChan.RemoteAddr().String())

    for {

        tcpConn = <-connChan

        go Serve(tcpConn)

    }

}


func Serve(conn net.Conn) {

  // handle the connection

}


慕哥9229398
浏览 240回答 1
1回答

侃侃无极

只需稍微更改您的主要内容:ch := make(chan net.Conn)go handleClient(ch)for {&nbsp; &nbsp; conn, err := listen.Accept()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Error Accept: ", err.Error())&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; ch <- conn}for 循环是服务器的主循环,如果您不在其他地方退出服务器,它将永远运行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go