Skip to content

Instantly share code, notes, and snippets.

@montaro
Last active February 25, 2020 23:29
Show Gist options
  • Save montaro/217e2d365bfdaca4ecf726ffda7f7672 to your computer and use it in GitHub Desktop.
Save montaro/217e2d365bfdaca4ecf726ffda7f7672 to your computer and use it in GitHub Desktop.
go-tcp-client-server
package main
import (
"bufio"
"fmt"
"net"
"os"
)
func main() {
arguments := os.Args
if len(arguments) < 2 {
fmt.Println("Please provide a port number!")
return
}
port := ":" + arguments[1]
conn, err := net.Dial("tcp", "127.0.0.1"+port)
if err != nil {
fmt.Printf("error occurred when trying to connect to port: %s error: %s", port, err)
return
}
defer conn.Close()
reader := bufio.NewReader(os.Stdin)
fmt.Println("Connected...")
for {
line, _, err := reader.ReadLine()
if err != nil {
fmt.Println("error while reading form stdin", err)
return
}
line = append(line, '\n')
_, err = conn.Write(line)
if err != nil {
fmt.Println("Writing error:", err)
return
}
readLine, _, err := bufio.NewReader(conn).ReadLine()
if err != nil {
if err.Error() == "EOF" {
fmt.Println("Disconnected!")
return
}
fmt.Println("Error while reading from server: ", err)
return
}
fmt.Printf("> %s\n", readLine)
}
}
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
arguments := os.Args
if len(arguments) < 2 {
fmt.Println("please provide a port number!")
return
}
port := ":" + arguments[1]
l, err := net.Listen("tcp4", port)
if err != nil {
fmt.Printf("error occurred when trying to listen to port: %s error: %s", port, err)
return
}
defer l.Close()
fmt.Println("Server started...")
for {
c, err := l.Accept()
if err != nil {
fmt.Println("Accept error: ", err)
return
}
go handleConnection(c)
}
}
func handleConnection(c net.Conn) {
fmt.Printf("Serving... %s\n", c.RemoteAddr().String())
for {
line, _, err := bufio.NewReader(c).ReadLine()
if err != nil {
fmt.Println("Reader error:", err)
fmt.Printf(`"%s"`, line)
return
}
trimmedLine := strings.TrimSpace(string(line))
fmt.Println("Received: ", trimmedLine)
if trimmedLine == "STOP" {
break
}
c.Write([]byte(fmt.Sprintf("echo: %s\n", trimmedLine)))
}
c.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment