duandao3265 2015-12-03 20:26
浏览 41
已采纳

在关闭套接字或写入换行符之前,TCPConn Write不会执行任何操作

Calling TCPConn.Write without any newline or null byte delimiter doesn't seem to do anything until the socket or writer is closed.

In this example I'd expect conn.Write to trigger the read on the server as soon as the write is complete, but nothing happens until the socket is closed. If I Write a string with a newline character before writing the ones without it works fine. Is this intended behavior? Are delimiters required? Or am I just missing something here..

Server

package main

import (
    "log"
    "net"
)

func main() {
    addr, _ := net.ResolveTCPAddr("tcp4", ":8080")
    l, err := net.ListenTCP("tcp4", addr)
    if err != nil {
        log.Fatal(err.Error())
    }

    defer l.Close()

    for {
        var conn *net.TCPConn
        if conn, err = l.AcceptTCP(); err != nil {
            log.Println(err.Error())
            continue
        }

        log.Println("client connected")
        go handleConnection(conn)
    }
}

func handleConnection(conn *net.TCPConn) {
    defer conn.Close()

    for {
        var b = make([]byte, 128)
        bytesRead, err := conn.Read(b)
        if err != nil {
            break
        }

        log.Printf("got: %s
", string(b[:bytesRead]))
    }

    log.Println("client disconnected")
}

Client

package main

import (
    "log"
    "net"
    "time"
)

func main() {
    addr, _ := net.ResolveTCPAddr("tcp", "localhost:8080")
    conn, err := net.DialTCP("tcp", nil, addr)
    if err != nil {
        log.Fatal(err.Error())
    }

    // uncommenting the following line will make the following writes work as expected
    //conn.Write([]byte("hello world
"))

    for i := 0; i < 5; i++ {
        conn.Write([]byte("hello"))
        log.Println("wrote hello")
        time.Sleep(time.Second)
    }

    time.Sleep(time.Second)
    conn.Close()
}
  • 写回答

2条回答 默认 最新

  • dongzhan1492 2015-12-04 15:41
    关注

    Thanks for giving it a go, I ran it on a Ubuntu vm where it worked as expected. So, as of 1.5.1 for Windows, it seems to be a bug.

    Edit:

    Turns out it's Eset Smart Security's protocol filtering, go isn't the culprit

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。