TCP Server and Client Demo
2022/4/14 6:17:01
本文主要是介绍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 } } }
这篇关于TCP Server and Client Demo的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-13Slicm 框架怎么进行用户认证?-icode9专业技术文章分享
- 2024-11-13在查询时将 map_coord 列的值转换为字符串有哪些方法?-icode9专业技术文章分享
- 2024-11-13如何将微信地区改成自定义文案?-icode9专业技术文章分享
- 2024-11-13DNS 缓存存在问题有哪些症状和解决方法?-icode9专业技术文章分享
- 2024-11-13HTTP 状态码(405)-Method Not Allowed是什么意思?-icode9专业技术文章分享
- 2024-11-13HTTP 状态码(500)-Internal Server Error是什么意思?-icode9专业技术文章分享
- 2024-11-13在 Element UI 中无法修改 $confirm 的取消按钮文字是什么原因?-icode9专业技术文章分享
- 2024-11-13unity XR是什么?-icode9专业技术文章分享
- 2024-11-13伴随矩阵是什么?-icode9专业技术文章分享
- 2024-11-13怎么使用grep -E 来查找匹配最后 2 条数据?-icode9专业技术文章分享