【发布时间】:2018-12-17 15:48:00
【问题描述】:
Go 新手并试图使 TCP 服务器并发。我发现了多个这样的例子,包括this one,但我想弄清楚为什么我对非并发版本所做的一些更改不起作用。
这是我开始的原始示例代码
package main
import "bufio"
import "fmt"
import "log"
import "net"
import "strings" // only needed below for sample processing
func main() {
fmt.Println("Launching server...")
fmt.Println("Listen on port")
ln, err := net.Listen("tcp", "127.0.0.1:8081")
if err != nil {
log.Fatal(err)
}
defer ln.Close()
fmt.Println("Accept connection on port")
conn, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
fmt.Println("Entering loop")
// run loop forever (or until ctrl-c)
for {
// will listen for message to process ending in newline (\n)
message, _ := bufio.NewReader(conn).ReadString('\n')
// output message received
fmt.Print("Message Received:", string(message))
// sample process for string received
newmessage := strings.ToUpper(message)
// send new string back to client
conn.Write([]byte(newmessage + "\n"))
}
}
上述方法有效,但不是并发的。
这是我修改后的代码
package main
import "bufio"
import "fmt"
import "log"
import "net"
import "strings" // only needed below for sample processing
func handleConnection(conn net.Conn) {
fmt.Println("Inside function")
// run loop forever (or until ctrl-c)
for {
fmt.Println("Inside loop")
// will listen for message to process ending in newline (\n)
message, _ := bufio.NewReader(conn).ReadString('\n')
// output message received
fmt.Print("Message Received:", string(message))
// sample process for string received
newmessage := strings.ToUpper(message)
// send new string back to client
conn.Write([]byte(newmessage + "\n"))
}
}
func main() {
fmt.Println("Launching server...")
fmt.Println("Listen on port")
ln, err := net.Listen("tcp", "127.0.0.1:8081")
if err != nil {
log.Fatal(err)
}
//defer ln.Close()
fmt.Println("Accept connection on port")
conn, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
fmt.Println("Calling handleConnection")
go handleConnection(conn)
}
我的代码基于我发现的其他几个并发服务器示例,但是当我运行上述代码时,服务器似乎退出而不是运行 handleConnection 函数
正在启动服务器...
监听端口
接受端口上的连接
调用handleConnection
感谢任何反馈,因为我发现并使用相同的方法测试了类似的代码示例,同时调用函数来处理连接,工作正常;所以,想知道我修改后的代码与我看到的其他示例有什么不同,因为它们对我来说似乎是一样的。
我不确定是否是问题所在,但我尝试评论关闭延迟调用。这没有帮助。
谢谢。
【问题讨论】:
标签: go tcp concurrency