Last active
April 5, 2022 10:13
-
-
Save 2minchul/e11235944fe38470a4edd3afbd74ee76 to your computer and use it in GitHub Desktop.
Golang TCP server
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 ( | |
"encoding/hex" | |
"errors" | |
"flag" | |
"fmt" | |
"io" | |
"log" | |
"net" | |
) | |
func main() { | |
portPtr := flag.Int("p", 1024, "port") | |
address := fmt.Sprintf(":%d", *portPtr) | |
log.Printf("Starting server... 0.0.0.0:%d\n", *portPtr) | |
l, err := net.Listen("tcp", address) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer l.Close() | |
for { | |
conn, err := l.Accept() | |
if err != nil { | |
log.Println(err) | |
continue | |
} | |
go ConnHandler(conn) | |
} | |
} | |
func ConnHandler(conn net.Conn) { | |
defer func() { | |
if err := recover(); err != nil { | |
log.Println(err) | |
} | |
}() | |
defer conn.Close() | |
addr := conn.RemoteAddr() | |
log.Printf("(%s) connected\n", addr.String()) | |
buf := make([]byte, 4096) | |
for { | |
n, err := conn.Read(buf) | |
if err != nil { | |
if errors.Is(err, io.EOF) { | |
log.Printf("(%s) disconnected\n", addr.String()) | |
return | |
} | |
log.Println(err) | |
return | |
} | |
if n == 0 { | |
continue | |
} | |
data := buf[:n] | |
log.Printf("(%s) %s", addr.String(), hex.Dump(data)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment