去语言实现tcp客户端/服务端

  

/服务器。/


包主要   

进口(
“bufio”
“fmt”

“时间”“净”
)

  

函数main () {
var tcpAddr * net.TCPAddr

  
 <代码> tcpAddr, _=净。ResolveTCPAddr (“tcp”、“127.0.0.1:9999”)
  
  tcpListener _:=净。tcpAddr ListenTCP (tcp)
  
  推迟tcpListener.Close ()
  
  为{
  tcpConn犯错:=tcpListener.AcceptTCP ()
  如果犯错!=nil {
  继续
  }
  
  fmt。Println(“一个客户端连接:" + tcpConn.RemoteAddr () .String ())
  去tcpPipe (tcpConn)
  } 
  

}   

func tcpPipe(康涅狄格州* net.TCPConn) {
ipStr:=conn.RemoteAddr () .String ()
推迟func () {
fmt。Println(“断开连接:”+ ipStr)
conn.Close ()
} ()
读者:=bufio.NewReader(康涅狄格州)

  
 <代码> {
  消息,犯错:=reader.ReadString (“\ n”)
  如果犯错!=nil {
  返回
  }
  
  fmt.Println (string(消息)
  味精:=time.Now () .String () +“\ n”
  b:=[]字节(味精)
  conn.Write (b)
  } 
  

}   

/客户端。/


包主要   

进口(
“bufio”
“fmt”

“时间”“净”
)

  

var quitSemaphore陈bool

  

函数main () {
var tcpAddr *网。TCPAddr
TCPAddr _=净。ResolveTCPAddr (“tcp”、“127.0.0.1:9999”)

  
 <代码>康涅狄格州,_:=净。DialTCP (tcp, nil, tcpAddr)
  推迟conn.Close ()
  fmt.Println(“连接!”)
  
  去onMessageRecived(康涅狄格州)
  
  b:=[]字节(“\ n”)
  conn.Write (b)
  
  <-quitSemaphore  
  

}   

func onMessageRecived(康涅狄格州* net.TCPConn) {
读者:=bufio.NewReader(康涅狄格州)
{
味精,犯错:=reader.ReadString (“\ n”)
fmt.Println(味精)
如果犯错!=nil {
quitSemaphore <嬲?br/>打破
}
time . sleep (time.Second)
b:=[]字节(味精)
conn.Write (b)
}
}

去语言实现tcp客户端/服务端