为了账号安全,请及时绑定邮箱和手机立即绑定

无法从插槽中读取数据

无法从插槽中读取数据

Go
婷婷同学_ 2021-04-13 13:14:21
我正在尝试学习Go语言,并且正在编写一个简单的回显服务器。不过,我很难使它正常工作。func listen(server string) {    var buf []byte    listener, ok := net.Listen("tcp", server)    if ok != nil {        fmt.Fprintf(os.Stderr, "Could not listen on socket: %s\n", ok.String())        return    }    conn, ok := listener.Accept()    if ok != nil {        fmt.Fprintf(os.Stderr, "Could not accept connection on socket: %s\n", ok.String())        return    }    writelen, ok := conn.Write(strings.Bytes("Ready to receive\n"))    if ok != nil {        fmt.Fprintf(os.Stderr, "Could not write to socket: %s\n", ok.String())    } else {        fmt.Printf("Wrote %d bytes to socket\n", writelen)    }    for ;; {        readlen, ok := conn.Read(buf)        if ok != nil {            fmt.Fprintf(os.Stderr, "Error when reading from socket: %s\n", ok.String())            return        }        if readlen == 0 {            fmt.Printf("Connection closed by remote host\n")            return        }        fmt.Printf("Client at %s says '%s'\n", conn.RemoteAddr().String(), buf)    }}我从此函数获得以下输出:[nathan@ebisu ~/src/go/echo_server] ./6.out 1234Using port 1234Wrote 17 bytes to socketError when reading from socket: EOF这是我在客户端上看到的:[nathan@ebisu ~] telnet 127.0.0.1 1234Trying 127.0.0.1...Connected to 127.0.0.1.Escape character is '^]'.Ready to receiveConnection closed by foreign host.任何帮助将不胜感激(或指向资源的指针;套接字API上的go文档尚有待改进)。
查看完整描述

2 回答

?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

在您的示例中,buf必须具有确定的大小。您已将其声明为长度为0的切片。

声明为:

var buf = make([]byte, 1024)


查看完整回答
反对 回复 2021-04-26
  • 2 回答
  • 0 关注
  • 228 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信