Last active
May 2, 2018 13:39
-
-
Save marc-harry/f6471e171a2d5e86017424f51f0b901b to your computer and use it in GitHub Desktop.
golang basic tcp communication
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 ( | |
| "flag" | |
| "fmt" | |
| "io/ioutil" | |
| "net" | |
| "os" | |
| ) | |
| const serverPort = 3000 | |
| var nodeID string | |
| func main() { | |
| nodeID = getPort() | |
| go startServer() | |
| if nodeID != "3000" { | |
| count := 0 | |
| for count < 10 { | |
| // Send concurrently if order not needed | |
| go sendMessage(fmt.Sprintf("%d: Hello from - %s", count, nodeID)) | |
| count++ | |
| } | |
| } | |
| fmt.Println("Listening...(Press Ctrl+C to close)") | |
| for { | |
| } | |
| } | |
| func sendMessage(message string) { | |
| conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", serverPort)) | |
| if err != nil { | |
| fmt.Println("Unable to send messsage") | |
| return | |
| } | |
| defer conn.Close() | |
| _, sendErr := conn.Write([]byte(message)) | |
| if sendErr != nil { | |
| fmt.Println(sendErr) | |
| } | |
| } | |
| func startServer() { | |
| nodeAddress := fmt.Sprintf("localhost:%s", nodeID) | |
| ls, err := net.Listen("tcp", nodeAddress) | |
| if err != nil { | |
| fmt.Println(err) | |
| } | |
| defer ls.Close() | |
| for { | |
| conn, err := ls.Accept() | |
| if err != nil { | |
| fmt.Println(err) | |
| continue | |
| } | |
| go handleConnection(conn) | |
| } | |
| } | |
| func getPort() string { | |
| nodeIDVar := flag.String("port", "3000", "port to run server on (Required)") | |
| flag.Parse() | |
| if nodeIDVar == nil { | |
| fmt.Println("1. No port provided") | |
| os.Exit(1) | |
| } | |
| nodeID := *nodeIDVar | |
| if nodeID == "" { | |
| fmt.Println("2. No port provided") | |
| os.Exit(1) | |
| } | |
| fmt.Printf("Running on port: %s\n", nodeID) | |
| return nodeID | |
| } | |
| func handleConnection(conn net.Conn) { | |
| defer conn.Close() | |
| request, err := ioutil.ReadAll(conn) | |
| if err != nil { | |
| fmt.Println(err) | |
| return | |
| } | |
| data := string(request) | |
| fmt.Println(data) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment