服务端:
package main import ( "fmt" "net" ) func process(conn net.Conn){ defer conn.Close(); for { fmt.Printf("服务器在等待客户端%s输入信息",conn.RemoteAddr().String()); buf:=make([]byte,1024); n,err:=conn.Read(buf);//如果没有发信息一致等着 if err !=nil { return; fmt.Println("error"); } content:=string(buf[:n]); fmt.Print(content); } } func main(){ fmt.Println("服务器启动...."); listen,err:=net.Listen("tcp","0.0.0.0:8888"); if err != nil { fmt.Println("listen err=",err); } defer listen.Close(); for{ fmt.Println("等待客户端来进行连接..."); conn,err:= listen.Accept(); if err != nil { fmt.Println("conn is error"); ipaddr:=conn.RemoteAddr().String(); fmt.Printf("accept() suc con =%v",ipaddr); } go process(conn); } }
客户端:
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main(){
conn,err:=net.Dial("tcp","127.0.0.1:8888");
if err!= nil {
fmt.Printf("client is error ");
return;
}
//给客户端发送数据
reader:=bufio.NewReader(os.Stdin);//代表标准输入
for {
content, err := reader.ReadString(' ');
content = strings.Trim(content," ");
if err != nil {
fmt.Printf("read is error");
}
if content == "exit" {
fmt.Println("客户端退出");
break;
}
_,err = conn.Write([]byte(content+" "));
if err != nil {
fmt.Println("send is error");
}
}
}