Creating a TCP client in golang
Here is a simple solution if you want to read all received data.
connbuf := bufio.NewReader(c.m_socket)
// Read the first byte and set the underlying buffer
b, _ := connbuf.ReadByte()
if connbuf.Buffered() > 0 {
var msgData []byte
msgData = append(msgData, b)
for connbuf.Buffered() > 0 {
// read byte by byte until the buffered data is not empty
b, err := connbuf.ReadByte()
if err == nil {
msgData = append(msgData, b)
} else {
log.Println("-------> unreadable caracter...", b)
}
}
// msgData now contain the buffered data...
}
bufio.NewReader
should be used only once, in your case, just before the for
. For example connbuf := bufio.NewReader(conn)
. Then you can use ReadString on connbuf, that returns the string and maybe an error. For example:
connbuf := bufio.NewReader(conn)
for{
str, err := connbuf.ReadString('\n')
if err != nil {
break
}
if len(str) > 0 {
fmt.Println(str)
}
}
I'm checking len
and err
because ReadString
may return data and an error (connection error, connection reset, etc.) so you need to check both.