Created
August 25, 2019 13:54
-
-
Save miguelbemartin/2fde07896d34b3ff45a4be3acab6d651 to your computer and use it in GitHub Desktop.
A TCP Server/Client written in Go
This file contains hidden or 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" | |
) | |
func main() { | |
// Connect to TCP Server | |
conn, err := net.Dial("tcp", ":8080") | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
// Close the connection when the application finish. | |
defer conn.Close() | |
// Create a loop to interact with the server | |
for { | |
// Read input from stdin | |
reader := bufio.NewReader(os.Stdin) | |
fmt.Printf("Enter a name: ") | |
text, err := reader.ReadString('\n') | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
// Send to server | |
fmt.Fprintf(conn, text + "\n") | |
// Listen the response | |
message, err := bufio.NewReader(conn).ReadString('\n') | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("Server response: " + message) | |
} | |
} |
This file contains hidden or 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" | |
"strings" | |
) | |
func main() { | |
// Create a TCP Server using the port 8080 | |
listener, err := net.Listen("tcp", ":8080") | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("Server started. Listening on 8080\n") | |
// Close the listener when the application finish. | |
defer listener.Close() | |
// Create a go routine for each connection | |
for { | |
conn, err := listener.Accept() | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
go handleConnection(conn) | |
} | |
} | |
func handleConnection(conn net.Conn) { | |
fmt.Printf("Client connected from %s\n", conn.RemoteAddr().String()) | |
// Create a loop to interact with the client | |
for { | |
data, err := bufio.NewReader(conn).ReadString('\n') | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
name := strings.TrimSpace(string(data)) | |
if len(name) == 0 { | |
// Missing the name. Return a message. | |
conn.Write([]byte(string("Please provide a name\n"))) | |
} else{ | |
// Name received. Return the message. | |
result := "Hello, " + name + "!\n" | |
conn.Write([]byte(string(result))) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment