在Golang中,为什么conn.Write的TCP响应为空?

huangapple go评论72阅读模式
英文:

In Golang, why is conn.Write tcp response empty?

问题

我有一个TCP服务器,它读取一个文件并将文件内容发送给客户端。

status.txt文件只包含一个布尔值。

当我使用curl时,它显示为true(带有前导空格)。

dat, err := ioutil.ReadFile("./status.txt")
conn.Write([]byte(" " + string(dat)))

而这段代码会导致curl: (52) Empty reply from server错误。

conn.Write([]byte(string(dat)))

你知道为什么会发生这种情况吗?我不想在响应字符串中添加空格。

英文:

I have a tcp server that reads a file that sends the file content to the client.

The 'status.txt' file contains only a boolean.

When I curl, this shows true (with leading space).

dat, err := ioutil.ReadFile("./status.txt")
conn.Write([]byte(" " + string(dat)))

Whereas this code results in curl: (52) Empty reply from server.

conn.Write([]byte(string(dat)))

Any clue why this happens? I don't want to have to pad my response string.

答案1

得分: 2

如果您不使用HTTP协议,请不要使用Curl。Curl期望的消息格式与HTTP协议兼容。
如果您发送文本"true",那肯定不是有效的HTTP头。

要测试TCP服务器,请改用Netcat:

nc localhost 端口
英文:

Don't use Curl if you are not using HTTP protocol. Curl is expecting certain format of the message that is compatible with HTTP protocol.
If you send text "true", that is for sure not valid HTTP Header.

To test TCP server use Netcat instead:

nc localhost port

huangapple
  • 本文由 发表于 2017年8月5日 14:38:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/45519075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定