douzhankui0758 2014-03-09 08:30
浏览 195
已采纳

Golang:同步对TCP套接字的读写

I'm trying to communicate with a TCP server which responds to messages:

package main

import (
    "net"
    "log"
)

func handleErr(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {

    // connect
    host := "1.2.3.4:5678"
    conn, err := net.Dial("tcp", host)
    handleErr(err)
    defer conn.Close()

    // write to socket
    message := "Test
"
    conn.Write([]byte(message))

    // read from socket
    // (assume response is 'Test
')
    reply := make([]byte, 1024)
    conn.Read(reply)
    log.Println(string(reply))

}

What I'm trying to accomplish is to send a message to the socket-server on the other end, wait for a response and then process it. I seem to be having trouble with properly syncing these write/read operation to be timed correctly - right now the read action seems to block the write; I'm assuming this happens due to the async nature of Go. What's an idiomatic way to do this? Is it goroutines? A continuous for { .. } loop for the reader? A sync.Wait mechanism? Help is appreciated. thanks.

  • 写回答

1条回答 默认 最新

  • dongye9991 2014-03-09 08:46
    关注

    Your code should work should work just fine. Golang is dead simple, there is no need for thinking about synchronizing read/write calls.

    [EDIT] To be clear: Golangs networking model is synchronous, just like any old style socket program. Golang uses internally efficient tricks to deal with it but as a programmer you have the comfort to program sequential code, which is the whole point about goroutines. Goroutines can be like threads but they are so cheap that you can create a LOT of them (a.k.a. fibers).

    Keep in mind that TCP might not send every piece in one shot. You should always check the return values to be sure that everything has been sent. Maybe the server just receives a part of the message and waits for more, but your client is already waiting for an answer? Just a guess..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog