在不同的机器上可以用TCP进行通信,在同一台机器上也可以,用客户端/服务端模式通信耦合度更低,golang示例多线程服务端和客户端通信,用C++写也可以
package main import ( "net" "fmt" "time" ) func server(){ listen_sock, err := net.Listen("tcp", "0.0.0.0:8888") if err != nil { fmt.Println("listen error") return; } defer listen_sock.Close() conn, err := listen_sock.Accept() if err != nil { fmt.Println("accept error") return; } defer conn.Close() buf := make([]byte, 100) for(true){ n, err := conn.Read(buf) if err != nil { fmt.Println("conn closed") return } fmt.Println("msg size:", n, string(buf[0:n])) } } func client(){ conn, err := net.Dial("tcp", "127.0.0.1:8888") if err != nil { fmt.Println("check server") return } defer conn.Close() for(true){ s := []byte("abc") conn.Write(s) time.Sleep(1 * time.Second) } } func main(){ go server() go client() time.Sleep(10 * time.Minute) }
结果:
go run main.go msg size: 3 abc msg size: 3 abc msg size: 3 abc