Skip to content

Instantly share code, notes, and snippets.

@vgangireddyin
Created May 26, 2016 18:24
Show Gist options
  • Save vgangireddyin/371b4123e79588d50d5c4b006ea5f624 to your computer and use it in GitHub Desktop.
Save vgangireddyin/371b4123e79588d50d5c4b006ea5f624 to your computer and use it in GitHub Desktop.
Simple TCP Server in Golang
package main
import (
"fmt"
"net"
"bufio"
"os"
)
func main() {
conn, _ := net.Dial("tcp", "127.0.0.1:8081")
reader := bufio.NewReader(os.Stdin)
fmt.Println("confess to server: ")
text, _ := reader.ReadString('\n')
fmt.Fprintf(conn, text + "\n")
reply, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Println("server respond like: " + reply)
}
package main
import (
"fmt"
"net"
"bufio"
)
func main() {
fmt.Println("init server")
l, _ := net.Listen("tcp", ":8081")
for {
conn, _ := l.Accept()
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
msg, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Println("message recieved: "+ msg)
newmsg := "RESP:" + msg
fmt.Println("sending new message: "+ newmsg)
conn.Write([]byte(newmsg))
conn.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment