A
A
Arseny Sokolov2016-03-17 13:48:25
go
Arseny Sokolov, 2016-03-17 13:48:25

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()
}

Now, if conn.Close() is removed in the handleServer () function , then the connection does not break, but it does not read anything more than the first line, however, as I thought it should have read each line.
How can I read all the lines one by one?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2016-03-17
@ArsenBespalov

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 question

Ask a Question

731 491 924 answers to any question