svr :
package main
import (
"bufio"
"fmt"
"net"
"strings"
)
func main() {
fmt.Println("Launching server...")
ln, _ := net.Listen("tcp", ":8081")
conn, _ := ln.Accept()
for {
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message Received:", string(message))
newmessage := strings.ToUpper(message)
conn.Write([]byte(newmessage + "\n"))
}
}
cli:
package main
import (
"bufio"
"fmt"
"net"
"os"
)
func main() {
conn, _ := net.Dial("tcp", "127.0.0.1:8081")
for {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Text to send:")
text, _ := reader.ReadString('\n')
fmt.Fprintf(conn, text+"\n")
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message from server:" + message)
}
}
有疑问加站长微信联系(非本文作者)