How to Use Go Scanner for Delimited TCP Data

Priyansh SaoPriyansh Sao
2 min read

This program creates a small TCP server and client inside the same application. The server sends a text message to the client. On the client side, the connection is wrapped in a scanner which reads the incoming stream and splits it into words (using spaces and punctuation as delimiters). The client collects these words, compares them with an expected list to check correctness, and finally prints them.

👉 In short: it’s a demo of sending data over TCP and reading it back as delimited tokens using bufio.Scanner.

package main

import (
    "fmt"
    "net"
    "bufio"
    "reflect"
)

func main() {
    //creating a payload
    payload := "this is a, hello world message."

    //start the listening server
    listener, err := net.Listen("tcp", "127.0.0.1:8080")
    if err != nil {
        fmt.Println("[server] unable to create a listener")
        return
    }
    defer listener.Close()
    fmt.Printf("[main] server listening on port: %s\n", listener.Addr().String())

    go func() {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("[server] unable to listen for client connection")
            return
        } 
        defer conn.Close()
        fmt.Println("[server] client connected")

        // writing payload to the client
        n, err := conn.Write([]byte(payload))
        if err != nil {
            fmt.Println("[server] unable to write to client")
            return
        }

        fmt.Printf("[server] success in writing(%d bytes)\n", n)
    }()

    // connecting client
    conn, err := net.Dial("tcp", listener.Addr().String())
    if err != nil {
        fmt.Println("[main] unable to create client")
        return
    }
    defer conn.Close()

    // creating a new scanner with conn as input
    scanner := bufio.NewScanner(conn)
    scanner.Split(bufio.ScanWords) //this code considers the whitespaces and "." as delimiters 

    var words []string // creating a array to store scanned words

    for scanner.Scan() { // this scans until the server returns error which io.EOF
        words = append(words, scanner.Text())
    }

    err = scanner.Err()
    if err != nil {
        fmt.Println("[client] unable to scan data")
    }

    expected := []string{"this", "is", "a,", "hello", "world", "message."}

    if !reflect.DeepEqual(words, expected) {
        fmt.Println("[client] the scanned words are not accurate!")
    }

    fmt.Printf("[client] scanned words: %v", words)
}

Output:

[main] server listening on port: 127.0.0.1:8080
[server] client connected
[server] success in writing(31 bytes)
[client] scanned words: [this is a, hello world message.]
0
Subscribe to my newsletter

Read articles from Priyansh Sao directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Priyansh Sao
Priyansh Sao