DEV Community

BC
BC

Posted on

Golang: a simple echo server

#go

It is really easy to write a TCP Echo server in Go.

package main

import (
    "io"
    "log"
    "net"
)

func main() {
    addr := "localhost:9999"
    server, err := net.Listen("tcp", addr)
    if err != nil {
        log.Fatalln(err)
    }
    defer server.Close()

    log.Println("Server is running on:", addr)

    for {
        conn, err := server.Accept()
        if err != nil {
            log.Println("Failed to accept conn.", err)
            continue
        }

        go func(conn net.Conn) {
            defer func() {
                conn.Close()
            }()
            io.Copy(conn, conn)
        }(conn)
    }
}
Enter fullscreen mode Exit fullscreen mode

We used io.Copy here to copy from conn as Reader to conn as Writer (conn implemented the ReadWriter interface)

Run it:

$ go run main.go
Enter fullscreen mode Exit fullscreen mode

Then in another terminal, test it with telnet:

$ telnet localhost 9999
Trying ::1...
telnet: connect to address ::1: Connection refused
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hello
hello
can you repeat this after me?
can you repeat this after me?
Enter fullscreen mode Exit fullscreen mode

Top comments (0)