dsy19890123 2014-09-27 17:47
浏览 88
已采纳

Go中客户端和服务器之间的通信

I'm a bit confused in how to do a client to send a string to a server, both in Go. When the server run ioutil.ReadAll(conexao) everything stop.

Server

    conexao, _ := listener.Accept()

    fmt.Printf("Conexão aceita %s
", conexao.RemoteAddr())

    frase, _ := ioutil.ReadAll(conexao)
    fmt.Println("Frase recebida")

    convertida := strings.ToUpper(string(frase))

    conexao.Write([]byte(convertida))

    conexao.Close()

Client

conexao, _ := net.DialTCP("tcp", nil, enderecoTCPServidor)

fmt.Println("Conexão Estabelecida")

conexao.Write([]byte("Gato de Botas!"))
fmt.Println("Frase enviada")

maiuscula, _ := ioutil.ReadAll(conexao)

fmt.Println("Maiuscula ",string(maiuscula))
  • 写回答

2条回答 默认 最新

  • doolo00026 2014-09-28 15:09
    关注

    The server is blocked reading data from the client, even though the server has read the complete request from the client. The client is blocked reading data from the server. To fix this issue, the server must stop reading after the complete request is read.

    One way to fix for this issue is for the client to close the write side of the socket when the client is done writing the request. This will cause the server to stop reading at the end of the message. Here's the one line change for this fix:

    conexao, _ := net.DialTCP("tcp", nil, enderecoTCPServidor)
    fmt.Println("Conexão Estabelecida")
    conexao.Write([]byte("Gato de Botas!"))
    conexao.CloseWrite()   // <------- Add this line
    fmt.Println("Frase enviada")
    maiuscula, _ := ioutil.ReadAll(conexao)
    fmt.Println("Maiuscula ",string(maiuscula))
    

    I created a working example on the playground.

    Another way to fix this issue is to add message framing to the request as in HTTP and many other protocols. Framing encodes within the message information about where the message ends. This can be a message length or a distinguished byte sequence indicating the end of the message. The server is modified to read to the end of a message and then respond to the client.

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

报告相同问题?

悬赏问题

  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services