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 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计