同步读写TCP套接字

huangapple go评论91阅读模式
英文:

Synchronize reads and writes to TCP socket

问题

我正在尝试与一个响应消息的TCP服务器进行通信:

package main

import (
    "net"
    "log"
)

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

func main() {

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

    // 写入套接字
    message := "Test\n"
    conn.Write([]byte(message))

    // 从套接字读取
    // (假设响应是'Test\n')
    reply := make([]byte, 1024)
    conn.Read(reply)
    log.Println(string(reply))

}

我想要实现的目标是向另一端的套接字服务器发送一条消息,等待响应,然后处理它。我似乎在正确同步这些写入/读取操作以正确计时方面遇到了问题 - 目前读取操作似乎会阻塞写入操作;我猜测这是由于Go的异步性质导致的。有没有一种惯用的方法来解决这个问题?是使用goroutine吗?还是使用一个连续的for { ... }循环来进行读取?还是使用sync.Wait机制?感谢您的帮助。谢谢。

英文:

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\n"
    conn.Write([]byte(message))

    // read from socket
    // (assume response is 'Test\n')
    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

得分: 1

你的代码应该能正常工作。Golang非常简单,不需要考虑同步读写调用的问题。

[编辑] 明确一下:Go的网络模型是同步的,就像任何旧式的套接字程序一样。Go在内部使用高效的技巧来处理它,但作为程序员,你可以编写顺序代码,这就是goroutine的全部意义。Goroutine可以像线程一样,但它们非常廉价,你可以创建很多(也称为fibers)。

请记住,TCP可能不会一次发送完所有的数据。你应该始终检查返回值,确保所有数据都已发送。也许服务器只接收到部分消息并等待更多,但你的客户端已经在等待答案?这只是一个猜测。

英文:

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: Go's networking model is synchronous, just like any old style socket program. Go 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.

huangapple
  • 本文由 发表于 2014年3月9日 16:30:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/22280060.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定