dqc22586 2013-07-29 04:15
浏览 133
已采纳

立即写入后,golang tcp套接字不发送消息

My GO version is 1.1.1

the sever recieved messages after connection close, but NoDelay was setted.

Is there something wrong

addr, _ := net.ResolveTCPAddr("tcp", "localhost:5432")
conn, err := net.DialTCP("tcp", nil, addr)
defer conn.Close()
if err != nil {
    fmt.Println("connect fail")
    return
}
err = conn.SetNoDelay(true)
if err != nil {
    fmt.Println(err.Error())
}

for {
    var message string
    _, err := fmt.Scanln(&message)
    if err != nil && err.Error() != "unexpected newline" {
        fmt.Println("input finished", err)
        break
    }

    if message == "" {
        fmt.Println("no input, end")
        break
    }
    // message = fmt.Sprintf("%s
",message) 
    //fmt.Fprintf(conn, message) // send immediately but following message won't send any more
    conn.Write([]byte(message)) // won't send until connection close
}
  • 写回答

2条回答 默认 最新

  • dousheng3364 2013-07-29 04:56
    关注

    There doesn't seem to be anything vitally wrong with your code so I'm guessing the error is on the server end.

    If you create a local TCP server on port 5432 you can test this.

    Try running the below server code and then test your client code against it. It just echos all received data to stdout.

    package main
    
    import (
        "io"
        "log"
        "net"
        "os"
    )
    
    func main() {
        l, err := net.Listen("tcp", "localhost:5432")
        if err != nil {
            log.Fatal(err)
        }
        defer l.Close()
        for {
            conn, err := l.Accept()
            if err != nil {
                log.Fatal(err)
            }
            go func(c net.Conn) {
                defer c.Close()
                io.Copy(os.Stdout, c)
            }(conn)
        }
    }
    

    You should see each line sent to the client printed (without the newline) as soon as you hit enter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作