duanjurong1347 2018-10-15 17:30
浏览 262

Golang同时从TCP连接读取

I am having some issue with a Go project. The code is way too big to copy and paste so I will try to explain as well as I can.

My program first connects to a TCP server, then it starts a goroutine passing as argument the connection object.

What I'm trying to achieve is having the client to read infinitely from the tcp connection while at the same time to take user input and communicate to the server by sending a retrieving data. I've tried using another goroutine but the program blocks whenever trying to retrieve data from the server.

Here is a reproduction of the error on go playground.

https://play.golang.org/p/OD5ozCRmy_4 server

https://play.golang.org/p/t1r_BAQM-jn client

Basically whenever the client tries to read from the connection it gets stuck. Thank you for your help.

  • 写回答

1条回答 默认 最新

  • douci1677 2018-10-17 21:51
    关注

    You should use channel here is a sample which can receive some connection and each connection could send data as wish

    package tcp

    import (
        "bufio"
        "fmt"
        "net"
        "strconv"
    
        "../log"
    
        "../config"
        "../controllers"
        h "../helpers"
        )
    
        type msgFormat struct {
          text []byte
          net.Conn
        }
    
    var accounts = make(map[net.Conn]int)
    var conns = make(chan net.Conn)
    var dconns = make(chan net.Conn)
    var msgs = make(chan msgFormat)
    var i int
    
    //Init is first point
    func Init() {
        startserver()
        for {
            select {
            case conn := <-conns:
                handleconnect(conn)
            case msg := <-msgs:
                go handlemsg(msg)
            case dconn := <-dconns:
                handlediscounect(dconn)
            }
        }
    }
    func handlemsg(incomemsg msgFormat) {
        logger.Log.Println(string(incomemsg.text))
        resp, err := controllers.Do(incomemsg.text)
        if err != nil {
            logger.Log.Println(err.Error())
        }
        strLen := []byte(h.Lpad(string(fmt.Sprintf("%v", len(resp))), "0", 4))
        //
        fresponse := append(strLen, resp...)
    
        incomemsg.Write(fresponse)
        logger.Log.Println("response is %v" , string(fresponse))
    }
    
    func startserver() {
        conf := config.GetConfigInstance()
    
        ln, err := net.Listen(conf.SERVER.Nettype, conf.SERVER.Address)
        if err != nil {
            logger.Log.Println(err.Error())
        }
        logger.Log.Printf("server is serving at %v", conf.SERVER.Address)
        go func() {
            for {
                conn, err := ln.Accept()
                if err != nil {
                    logger.Log.Println(err.Error())
                }
                conns <- conn
            }
        }()
    
    }
    
    func readdate(conn net.Conn, i int) {
        for {
            rd := bufio.NewReader(conn)
    
            dataLen := make([]byte, 4)
            _, err := rd.Read(dataLen)
            if err != nil {
                break
            }
            intLen, _ := strconv.Atoi(string(dataLen))
            data := make([]byte, intLen)
            _, err = rd.Read(data)
            if err != nil {
                break
            }
            msgs <- msgFormat{data, conn}
        }
        dconns <- conn
    }
    
    func handleconnect(newconnection net.Conn) {
        accounts[newconnection] = i
        i++
        // if addr , ok := newconnection.RemoteAddr().str
        logger.Log.Printf("Action: Client_Connected %v is connected via %v 
    ", i, newconnection.RemoteAddr().(*net.TCPAddr).IP)
        go readdate(newconnection, i)
    }
    
    func handlediscounect(disconnection net.Conn) {
        logger.Log.Printf("Action: Client_Disconnected %v / %v is gone
    ", accounts[disconnection] + 1, disconnection.RemoteAddr().(*net.TCPAddr).IP)
        delete(accounts, disconnection)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥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
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题