Created
September 12, 2023 20:14
-
-
Save jaxlo/2d24e844dbfb314d652f9254daef0b4d to your computer and use it in GitHub Desktop.
Simple tcp client/server example in Go
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 ( | |
"bufio" | |
"fmt" | |
"net" | |
"os" | |
"strings" | |
"time" | |
) | |
func main() { | |
fmt.Println("Welcome to Prenet 0.0.1") | |
fmt.Println("Enter an option:\n (1) Client\n (2) Server") | |
var running_as string | |
fmt.Scan(&running_as) | |
if running_as == "1" { | |
client() | |
} else if running_as == "2" { | |
server() | |
} else { | |
fmt.Println("Error: Invalid running type") | |
return | |
} | |
} | |
func client() { | |
fmt.Println("Client starting...") | |
CONNECT := "127.0.0.1:1337" | |
c, err := net.Dial("tcp", CONNECT) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
for { | |
reader := bufio.NewReader(os.Stdin) | |
fmt.Print(">> ") | |
text, _ := reader.ReadString('\n') | |
fmt.Fprintf(c, text+"\n") | |
message, _ := bufio.NewReader(c).ReadString('\n') | |
fmt.Print("->: " + message) | |
if strings.TrimSpace(string(text)) == "STOP" { | |
fmt.Println("TCP client exiting...") | |
return | |
} | |
} | |
} | |
func server() { | |
fmt.Println("Server starting...") | |
PORT := ":" + "1337" | |
l, err := net.Listen("tcp", PORT) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
defer l.Close() | |
c, err := l.Accept() | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
for { | |
netData, err := bufio.NewReader(c).ReadString('\n') | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
if strings.TrimSpace(string(netData)) == "STOP" { | |
fmt.Println("Exiting TCP server!") | |
return | |
} | |
fmt.Print("-> ", string(netData)) | |
t := time.Now() | |
myTime := t.Format(time.RFC3339) + "\n" | |
c.Write([]byte(myTime)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment