Skip to content

Instantly share code, notes, and snippets.

@nilesh-akhade
Created April 8, 2022 10:16
Show Gist options
  • Save nilesh-akhade/225b7ea791fc71460c375f2027cdb45a to your computer and use it in GitHub Desktop.
Save nilesh-akhade/225b7ea791fc71460c375f2027cdb45a to your computer and use it in GitHub Desktop.
Write a program that runs a TCP service to reverse a string
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
arguments := os.Args
if len(arguments) == 1 {
fmt.Println("Please provide a port number!")
return
}
port := ":" + arguments[1]
fmt.Printf("Listening on %v\n", port)
l, err := net.Listen("tcp4", port)
if err != nil {
fmt.Println(err)
return
}
defer l.Close()
for {
c, err := l.Accept()
if err != nil {
fmt.Println(err)
return
}
go handleConnection(c)
}
}
func handleConnection(c net.Conn) {
fmt.Printf("Serving %s\n", c.RemoteAddr().String())
for {
netData, err := bufio.NewReader(c).ReadString('\n')
if err != nil {
fmt.Println(err)
return
}
temp := strings.TrimSpace(string(netData))
if temp == "stop" {
break
}
result := reverse(temp) + "\n"
c.Write([]byte(string(result)))
}
c.Close()
}
func reverse(in string) string {
var sb strings.Builder
runes := []rune(in)
for i := len(runes) - 1; 0 <= i; i-- {
sb.WriteRune(runes[i])
}
return sb.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment