Trouble with exiting a for loop that contains bufio.NewScanner.Scan()

560 views
Skip to first unread message

Trig

unread,
Dec 30, 2018, 7:35:49 PM12/30/18
to golang-nuts
I'm currently utilizing the bufio.NewScanner to read ASCII data from a serial port.  I have the following simple code:

ns := bufio.NewScanner(sPort)

for {
   ns.Scan()
   if ns.Text() != "" { // ignore blank lines
      // handle content here
   }
}

The problem is ns.Scan() blocks the loop from continuing if there isn't any data.  This leaves me unable to break out of the loop with a for condition or a select statement also within the loop which is looking for a close command from a channel before or after it, etc.  Am I doing something wrong, or is there a proper way to handle this?

Wagner Riffel

unread,
Dec 30, 2018, 7:48:21 PM12/30/18
to Trig, golang-nuts
Scan() returns false when it reaches EOF or an error, so with what you
provided i assume you're missing to check that.
for ns.Scan() {
...
}

or

for {
if !ns.Scan() {
break
}

-wgr
> --
> You received this message because you are subscribed to the Google Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Trig

unread,
Dec 30, 2018, 9:19:22 PM12/30/18
to golang-nuts
When reading from a serial port, there is no EOF between data sets.  I may have to use something else besides a scanner to do this.  I have a handler function called by a goroutine that just monitors incoming data in a for loop and sends that data coming in back through a channel.  If the connection closes, I need a way to signal this loop to close so that the function can return and end.

Michael Jones

unread,
Dec 30, 2018, 11:06:14 PM12/30/18
to Trig, golang-nuts
You are ignoring an important situational fact...the serial port is not an infinite stream to you, but a sequence of serial ports divided by connection closings. In this situation, the thing to be scanned is experiencing EOF at close events but this is not being communicated. That is the problem. Need to send EOF to the scanner (naturally) by creating a reader that emits EOF on close. 
--
Michael T. Jones
michae...@gmail.com
Reply all
Reply to author
Forward
0 new messages