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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)