Ado Ren
Ado Ren

Reputation: 4414

Write multiple time on TCP conn

I have a TCP server server : l, err := net.Listen("tcp", "localhost:"+strconv.Itoa(tcpPort))

The server listens to incoming client requests as is :

    for {
        c, err := l.Accept()
        if err != nil {
            log.Fatal(err)
        }
        b := make([]byte, 1024)
        c.Read(b)
        fmt.Println(string(b)) // "Hello"
    }

I have a client : conn, err := net.Dial("tcp", address)

Now I I write once with conn.Write([]byte("Hello"))

The server catches Hello. But if I have these :

_, err := conn.Write([]byte("Hello"))
if err != nil {
    log.Fatal(err)
}

_, err = conn.Write([]byte("World"))
if err != nil {
    log.Fatal(err)
}

Then I will get Hello, but not World.

How can I write multiple time on the same connection ?

Full function below

func main() {
    l, err := net.Listen("tcp", "localhost:1234")
    if err != nil {
        log.Fatal(err)
    }
    defer l.Close()

    go func() {
        for {
            c, err := l.Accept()
            if err != nil {
                log.Fatal(err)
            }
            b := make([]byte, 1024)
            c.Read(b)
            fmt.Println(string(b))
        }

    }()

    conn, err := net.Dial("tcp", "localhost:1234")
    if err != nil {
        log.Fatal(err)
    }
    _, err = conn.Write([]byte("hello"))
    if err != nil {
        log.Fatal(err)
    }
    _, err = conn.Write([]byte("world"))
    if err != nil {
        log.Fatal(err)
    }
}

Upvotes: 1

Views: 1048

Answers (2)

MenyT
MenyT

Reputation: 2275

Your problem is not with conn.Write but with reading from connection. Now you read just once from every new opened connection accepted by l.Accept(). Solution is to read repeatedly.

Your code is also limited to handle just one connection. And do not forget to check error from c.Read(b) to know when stop listen on this connection.

go func() {
    for {
        c, err := l.Accept()
        if err != nil {
            log.Fatal(err)
        }
        go func(conn net.Conn) {
            for {
                b := make([]byte, 1024)
                _, err := conn.Read(b)
                if err != nil {
                    if err != io.EOF {
                        fmt.Println("read error:", err)
                    }
                    break
                }
                fmt.Println(string(b))
            }
            fmt.Println("Stopping handle connection")
        }(c)
    }
}()

Upvotes: 1

aureliar
aureliar

Reputation: 1614

Your problem is in the server code, the one that receives data. It only reads once from the tcp stream. If you want it to read "world", replace the single read operation by a loop:

go func() {
    for {
        c, err := l.Accept()
        if err != nil {
            log.Fatal(err)
        }
        for {
            b := make([]byte, 1024)
            c.Read(b)
            fmt.Println(string(b))
      }
    }
}()

Upvotes: 2

Related Questions