Created
May 26, 2016 18:24
-
-
Save vgangireddyin/371b4123e79588d50d5c4b006ea5f624 to your computer and use it in GitHub Desktop.
Simple TCP Server in Golang
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 ( | |
"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) | |
} |
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 ( | |
"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