dongzhang7157 2018-07-09 21:37
浏览 159
已采纳

使Golang TCP服务器并发

New to Go and trying to make a TCP server concurrent. I found multiple examples of this, including this one, but what I am trying to figure out is why some changes I made to a non concurrent version are not working.

This is the original sample code I started from

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 (
)
    message, _ := bufio.NewReader(conn).ReadString('
')
    // 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 + "
"))
  }
}

The above works, but it is not concurrent.

This is the code after I modified it

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 (
)
    message, _ := bufio.NewReader(conn).ReadString('
')
    // 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 + "
"))
  }

}

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)

}

I based my code on several other examples I found of concurrent servers, but yet when I run the above the server seems to exit instead of running the handleConnection function

Launching server...

Listen on port

Accept connection on port

Calling handleConnection

Would appreciate any feedback as similar code examples I found and tested using the same approach, concurrently calling function to handle connections, worked; so, would like to know what is different with my modified code from the other samples I saw since they seem to be the same to me.

I was not sure if it was the issue, but I tried commenting the defer call to close. That did not help.

Thanks.

  • 写回答

3条回答 默认 最新

  • douzaipou3327 2018-07-09 22:02
    关注

    Your main function is returning immediately after accepting a new connection, so your program exits before the connection can be handled. Since you probably also want to receive more than one single connection (or else there would be no concurrency), you should put this in a for loop.

    You are also creating a new buffered reader in each iteration of the for loop, which would discard any buffered data. You need to do that outside the for loop, which I demonstrate here by creating a new bufio.Scanner which is a simpler way to read newline delimited text.

    import (
        "bufio"
        "fmt"
        "log"
        "net"
        "strings"
    )
    
    func handleConnection(conn net.Conn) {
        defer conn.Close()
        scanner := bufio.NewScanner(conn)
        for scanner.Scan() {
            message := scanner.Text()
            fmt.Println("Message Received:", message)
            newMessage := strings.ToUpper(message)
            conn.Write([]byte(newMessage + "
    "))
        }
    
        if err := scanner.Err(); err != nil {
            fmt.Println("error:", err)
        }
    }
    
    func main() {
        ln, err := net.Listen("tcp", "127.0.0.1:8081")
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Println("Accept connection on port")
    
        for {
            conn, err := ln.Accept()
            if err != nil {
                log.Fatal(err)
            }
            fmt.Println("Calling handleConnection")
            go handleConnection(conn)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀