dsy19890123 2014-09-27 09: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 07: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 MATLAB解决问题
  • ¥20 哪位专业人士知道这是什么原件吗?哪里可以买到?
  • ¥15 关于#c##的问题:treenode反序列化后获取不到上一节点和下一节点,Fullpath和Handle报错
  • ¥15 一部手机能否同时用不同的app进入不同的直播间?
  • ¥15 没输出运行不了什么问题
  • ¥20 输入import torch显示Intel MKL FATAL ERROR,系统驱动1%,: Cannot load mkl_intel_thread.dll.
  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目