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 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号