server
package main
import (
"fmt"
"net"
)
func Hello(name string) string {
return "HelloWorld" + name
}
func main() {
listener, err := net.Listen("tcp4", "127.0.0.1:6872")
if err != nil {
fmt.Println("Listen err:", err)
}
conn, err := listener.Accept()
if err != nil {
fmt.Println("Accept err:", err)
}
defer conn.Close()
funcMap := make(map[string]func(string) string)
funcMap["Hello"] = Hello
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("Read err:", err)
}
funcName := string(buf[:n])
n, err = conn.Read(buf)
if err != nil {
fmt.Println("Read err:", err)
}
funcArgs := string(buf[:n])
function := funcMap[string(funcName)]
result := function(string(funcArgs))
conn.Write([]byte(result))
}
client
package main
import (
"fmt"
"net"
"time"
)
func main(){
conn,err:=net.Dial("tcp4", "127.0.0.1:6872")
if err != nil {
fmt.Println("Dial err:", err)
}
conn.Write([]byte("Hello"))
time.Sleep(1*time.Second)
conn.Write([]byte("wxf"))
buf := make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
fmt.Println("Read err:", err)
}
fmt.Println(string(buf[:n]))
}