Answer the question
In order to leave comments, you need to log in
How to read multiple lines in Go without breaking connections?
There is this code:
func main() {
ln, _ := net.Listen("tcp", ":6556")
defer ln.Close()
for {
con, _ := ln.Accept()
go handleServer(conn)
}
}
func handleServer(conn net.Conn) {
buf := make([]byte, 0, 4096)
n, _ := conn.Read(buf)
log.Printf("Received line length: %d\n", n)
conn.Write([]byte("Message received.\n"))
conn.Close()
}
Answer the question
In order to leave comments, you need to log in
Here is an example code. Here we read incoming data line by line and send "Message received" after each line is read. Reading continues until the client closes the connection.
package main
import (
"bufio"
"log"
"net"
)
func main() {
ln, _ := net.Listen("tcp", ":6556")
defer ln.Close()
for {
conn, _ := ln.Accept()
go handleServer(conn)
}
}
func handleServer(conn net.Conn) {
reader := bufio.NewReader(conn)
defer conn.Close()
for {
line, err := reader.ReadString('\n')
if err != nil {
return
}
conn.Write([]byte("Message received.\n"))
log.Printf("Received line length: %d\n", len(line))
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question