dqan70724 2019-07-28 12:28
浏览 115
已采纳

向TCP服务器发送多个请求失败

I'm trying to send more than one request to a TCP server in Go but for some reason the second request is never sent, even if it is identical to the first one.

This is the server:

func StartServer(host string) {

    l, err := net.Listen("tcp", host)
    log.Println("Starting server on:", host)

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    defer l.Close()
    log.Println("Server is running...")

    for {
        // Listen for an incoming connection.
        conn, err := l.Accept()
        if err != nil {
            log.Fatal("Error accepting: ", err.Error())
        }
        // Handle connections in a new goroutine.
        fmt.Println("got a request")
        go handleRequest(conn)
    }
}

And this is the function in the client that sends the requests to the server:

func (u *User) ConnectToServer(host string, partner string) {
    conn, _ := net.Dial("tcp", host)
    fmt.Fprintf(conn, "message1
")
    fmt.Fprintf(conn, "message2
")
}

EDIT: In the handleRequest function I read the input as follows:

 // Handles incoming requests.
func handleRequest(conn net.Conn) {

    rec, err := bufio.NewReader(conn).ReadString('
')

    if err != nil {
        log.Println("Error reading:", err.Error())
    }

    log.Println("Got message: ", rec)

    // Send a response back to person contacting us.
    conn.Write([]byte("Message received."))
    // conn.Close()
}

Which according to the documentation only takes the first part before the first line break detected so I believe the second message is ignored because of this. How can I read both messages? Should I change the delimiter in the client maybe?

  • 写回答

2条回答 默认 最新

  • doqo89924 2019-07-28 21:32
    关注

    The server should read multiple lines given that the client sends multiple lines. Use bufio.Scanner to read lines:

    func handleRequest(conn net.Conn) {
       defer conn.Close()
       scanner := bufio.NewScanner(conn)
       for scanner.Scan() {
          fmt.Printf("Got message: %s
    ", scanner.Bytes())
          conn.Write([]byte("Message received."))
       }
       if err := scanner.Err(); err != nil {
          fmt.Printf("error reading connection: %v
    ", err)
       }
    }
    

    Some notes about the code:

    • To prevent a resource leak, the function closes the connection on return.
    • The scanner loop breaks on error reading the connection. If the error is not io.EOF, then the function logs the error.
    • bufio.Reader can also be used to read lines, but bufio.Scanner is easier to use.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。