douqiaolong0528 2018-03-10 06:10
浏览 341
已采纳

如何在golang中的单个TCP连接上同时进行读写?

I try to create a sigle TCP connection client used for multiple write and read concurrently. For example the TCP Server will return value like you write. The problem is the data exchanged between write and read. I have tried with sync.Mutex but it still doesn't work.

My Result is :

2018/03/10 12:52:10 STRING 4:1
2018/03/10 12:52:10 STRING 5:6
2018/03/10 12:52:10 STRING 2:3
and so on

My Expectation is :

2018/03/10 12:52:10 STRING 4:4
2018/03/10 12:52:10 STRING 5:5
2018/03/10 12:52:10 STRING 2:2
2018/03/10 12:52:10 STRING 3:3

Here's my code : package main

import (
    "bufio"
    "log"
    "net"
    "strconv"
    "sync"
    "time"
)

type Cc struct {
    mux sync.Mutex
    rw  *bufio.ReadWriter
}

func main() {
    addr := "127.0.0.1:3333"
    log.Println("Dial " + addr)
    conn, err := net.Dial("tcp", addr)
    cc := Cc{
        rw: bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)),
    }

    if err != nil {
        log.Println(err)
    }
    for i := 1; i <= 10; i++ {
        go testC(cc, strconv.Itoa(i))
    }

    time.Sleep(60 * time.Second)

}

func testC(cc Cc, st string) {
    cc.mux.Lock()
    defer cc.mux.Unlock()
    _, err := cc.rw.WriteString(st + "
")
    if err != nil {
        log.Println(err)
        // return errors.Wrap(err, "Could not send additional STRING data ("+strconv.Itoa(n)+" bytes written)")
    }
    // log.Println("Flush the buffer."s)
    err = cc.rw.Flush()
    if err != nil {
        log.Println(err)
        // return errors.Wrap(err, "Flush failed.")
    }

    time.Sleep(3 * time.Second)

    // Read the reply.
    // log.Println("Read the reply.")
    response, err := cc.rw.ReadString('
')
    if err != nil {
        log.Println(err)
        // return errors.Wrap(err, "Client: Failed to read the reply: '"+response+"'")
    }

    log.Println("STRING " + st + ":" + response)
    // cc.mux.Unlock()
}

Sorry for my bad English, Thank You.

  • 写回答

1条回答 默认 最新

  • duanluanlang8501 2018-03-10 08:57
    关注

    func testC(cc Cc, st string) actually takes a copy of cc. So, even with locking on a mutex, you actually locking on 10 copies of it which are totally independent. So, your locking code has no effect.

    Try changing testC function signature to func testC(cc *Cc, st string). And then your call go testC(&cc, strconv.Itoa(i)).

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化