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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程