TCP Server and Client Demo
server.go
package main
import (
"bufio"
"fmt"
"io"
"net"
"time"
)
func tcpPipe(conn *net.TCPConn) {
ipStr := conn.RemoteAddr().String()
defer func() {
fmt.Println("Disconnected:" + ipStr)
conn.Close()
}()
reader := bufio.NewReader(conn)
i := 0
for {
message, err := reader.ReadString('\n')
if err != nil || err == io.EOF {
break
}
fmt.Println(string(message))
time.Sleep(time.Second * 1)
msg := time.Now().String() + conn.RemoteAddr().String() + "Server Say Hello!\n"
b := []byte(msg)
conn.Write(b)
i++
if i > 10 {
break
}
}
}
// 服务端代码
func main() {
var tcpAddr *net.TCPAddr
tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:9999")
tcpListener, _ := net.ListenTCP("tcp", tcpAddr)
defer tcpListener.Close()
fmt.Println("Server ready to read ...")
for {
tcpConn, err := tcpListener.AcceptTCP()
if err != nil {
fmt.Println("accept error:", err)
continue
}
fmt.Println("A client connected:" + tcpConn.RemoteAddr().String())
// 每来一个连接就开启一个协程来管理
go tcpPipe(tcpConn)
}
}
client.go
package main
import (
"bufio"
"fmt"
"io"
"net"
"time"
)
func main() {
var tcpAddr *net.TCPAddr
tcpAddr, _ = net.ResolveTCPAddr("tcp", "127.0.0.1:9999")
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
fmt.Println("Client connect error!" + err.Error())
return
}
defer conn.Close()
fmt.Println(conn.LocalAddr().String() + ":Client connected!")
onMessageRecived(conn)
}
func onMessageRecived(conn *net.TCPConn) {
reader := bufio.NewReader(conn)
b := []byte(conn.LocalAddr().String() + "Say hello to Server...\n")
conn.Write(b)
for {
msg, err := reader.ReadString('\n')
fmt.Println("ReadString")
fmt.Println(msg)
if err != nil || err == io.EOF {
fmt.Println(err)
break
}
time.Sleep(time.Second * 2)
fmt.Println("writing....")
b := []byte(conn.LocalAddr().String() + "write data to Server...\n")
_, err = conn.Write(b)
if err != nil {
fmt.Println(err)
break
}
}
}
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!