英文:
A go echo server using go channel, but no reply from the server
问题
我正在尝试使用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) {
// 处理连接
}
以上代码看起来没有明显的错误。它使用goroutine来接受连接并将其发送到handleClient函数进行处理。你可以检查一下其他部分的代码,例如Serve函数,确保连接的处理逻辑正确。另外,你可以尝试在代码中添加一些调试输出,以便更好地理解程序的执行流程和可能的问题。
英文:
I am trying to use go channel and goroutine to write an echo server, but there is no reply from the server. The following server listens on port 9090, and create a channel ch to receive connection acceptances, then it pass to handleClient to handle the connection details. Is the following code wrong? It has no errors when under 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
}
答案1
得分: 2
只需稍微修改你的主函数:
ch := make(chan net.Conn)
go handleClient(ch)
for {
conn, err := listen.Accept()
if err != nil {
fmt.Println("Error Accept:", err.Error())
return
}
ch <- conn
}
这个for循环是服务器的主循环,如果你没有在其他地方退出服务器,它将一直运行下去。
英文:
Just change your main a bit:
ch := make(chan net.Conn)
go handleClient(ch)
for {
conn, err := listen.Accept()
if err != nil {
fmt.Println("Error Accept: ", err.Error())
return
}
ch <- conn
}
The for loop is the server's main loop and will run forever if you do not exit the server somewhere else.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论