Last active
January 14, 2020 14:37
-
-
Save mtilson/1479d39c71f31c5d2c9335755bf2c36e to your computer and use it in GitHub Desktop.
how to create pure echo server - in about 20+ code lines [golang] [20lines]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net" | |
) | |
func handle(conn net.Conn) { | |
defer conn.Close() | |
var readBuf = make([]byte, 512) | |
var readCnt int | |
var err error | |
for { | |
if readCnt, err = conn.Read(readBuf); err != nil { break } | |
fmt.Printf("received: %s", string(readBuf)) | |
if _, err = conn.Write(readBuf[0:readCnt]); err != nil { break } | |
} | |
} | |
func main() { | |
socket, _ := net.Listen("tcp", ":8765") | |
for { | |
conn, _ := socket.Accept() | |
go handle(conn) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[shell-1 ]$ go run main.go | |
received: ECHO a | |
received: ECHO b | |
received: ECHO c | |
[shell-2 ]$ for i in a b c ; do echo "ECHO $i" | nc localhost 8765 ; done | |
ECHO a | |
ECHO b | |
ECHO c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment