Created
May 27, 2017 21:50
-
-
Save dima056359/e7c1892a0073e557750d3b965b5c46df to your computer and use it in GitHub Desktop.
Simple echo-server written in Golang
This file contains 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 ( | |
"log" | |
"net" | |
"strings" | |
) | |
// accepting connections | |
func main() { | |
ln, err := net.Listen("tcp", ":6000") | |
if err != nil { | |
log.Fatal(err) | |
} | |
for { | |
conn, err := ln.Accept() | |
if err != nil { | |
log.Println(err) | |
continue | |
} | |
go handleConnection(conn) | |
} | |
} | |
// handling the connection | |
func handleConnection(c net.Conn) { | |
buf := make([]byte, 4096) | |
for { | |
n, err := c.Read(buf) | |
if err != nil || n == 0 { | |
c.Close() | |
break | |
} | |
n, err = c.Write(buf[0:n]) | |
// push received message to the screen | |
log.Println(strings.TrimSpace(string(buf[:n]))) | |
if err != nil { | |
c.Close() | |
break | |
} | |
} | |
log.Printf("Connection from %v closed.", c.RemoteAddr()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment