Search code examples
gonetwork-programmingtcpconcurrencyserver

How to receive data separately from two concurrent processes running on a server?


I am trying to build a basic client/server architecture in which there is some exchange of data between the two and also some processing on both sides. So my server has two threads that are sending some data to the client side. I want to know how to receive this data separately into two different variables.

I have learnt, although I am still not sure, that this has something to do with concepts like race condition, mutex lock etc. I have a basic idea about them but have never used them practically. I want to know if there is some pre-designed solution regarding this problem.

Server Side:

func handleConn(conn net.Conn) {
    go func() {
        io.WriteString(conn, "Text 1")
    }()
    go func() {
        io.WriteString(conn, "Text 2")
    }()
}

Client Side:

func SocketClient(ip string, port string) {
    addr := strings.Join([]string{ip, port}, ":")
    conn, err := net.Dial("tcp", addr)

    defer conn.Close()

    if err != nil {
        log.Fatalln(err)
    }

    buff := make([]byte, 1024)
    n, _ := conn.Read(buff)
    log.Printf("Received: %s", buff[:n])
}

Both "Text 1" and "Text 2" are read by the variable buff. I want to make it like there are two separate variables buff1 and buff2 to hold both texts separately.


Solution

  • You read the connection just once and you should expect to receive the whole data in one call. You can separate your messages with a delimiter like newline and in a loop read the data by that delimiter. This way it's like you received two different messages . I made a sample for you to check out.

    package main
    
    import (
        "bufio"
        "io"
        "log"
        "net"
        "sync"
    )
    
    func handleConn(conn net.Conn) {
        go func() {
            io.WriteString(conn, "Text 1\n")
        }()
        go func() {
            io.WriteString(conn, "Text 2\n")
        }()
    }
    
    func SocketClient() {
        conn, err := net.Dial("tcp", ":3000")
        if err != nil {
            log.Fatal(err)
        }
        defer conn.Close()
        if err != nil {
            log.Fatalln(err)
        }
        reader := bufio.NewReader(conn)
        for {
            buff, err := reader.ReadString('\n')
            if err != nil {
                log.Fatalln(err)
            }
            log.Printf("Received: %s", buff)
        }
    }
    
    func main() {
        wg := &sync.WaitGroup{}
        wg.Add(1)
        go func() {
            a, _ := net.Listen("tcp", ":3000")
            wg.Done()
            for {
                conn, err := a.Accept()
                if err != nil {
                    log.Fatalln(err)
                }
                handleConn(conn)
            }
        }()
        wg.Wait()
        SocketClient()
    }
    

    Output:

    Received: Text 1
    Received: Text 2