golang实现tcp通信例子

tcp/udp ip通信是当前重要的通信方式。

当然对于golang开发者而言,实现tcp通信也是必要的。本文的内容主要是基于《Go语言四十二章经》地址:https://www.jianshu.com/nb/29056963的详细讲解
本文的例子分为服务端与客户端两部分:
服务端:

package main

import (
    "bufio"
    "fmt"
    "io"
    "net"
    "time"
)

//tcp server 服务端代码

func main() {
    //定义一个tcp断点
    var tcpAddr *net.TCPAddr
    //通过ResolveTCPAddr实例一个具体的tcp断点
    tcpAddr,_ = net.ResolveTCPAddr("tcp","127.0.0.1:9999")
    //打开一个tcp断点监听
    tcpListener,_ := net.ListenTCP("tcp",tcpAddr)
    defer tcpListener.Close()
    fmt.Println("Server ready to read ...")
    //循环接收客户端的连接,创建一个协程具体去处理连接
    for{
        tcpConn,err := tcpListener.AcceptTCP()
        if err!=nil {
            fmt.Println(err)
            continue
        }
        fmt.Println("A client connected :" +tcpConn.RemoteAddr().String())
        go tcpPipe(tcpConn)
    }
}
//具体处理连接过程方法
func tcpPipe(conn *net.TCPConn){
    //tcp连接的地址
    ipStr := conn.RemoteAddr().String()

    defer func() {
        fmt.Println(" Disconnected : " + ipStr)
        conn.Close()
    }()

    //获取一个连接的reader读取流
    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*3)

        msg := time.Now().String() + conn.RemoteAddr().String() + " Server Say hello! \n"

        b := []byte(msg)

        conn.Write(b)

        i++

        if i>10 {
            break
        }
    }
}


客户端

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!")

    onMessageReceived(conn)
}

func onMessageReceived(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
        }
    }
}

你可能感兴趣的:(golang实现tcp通信例子)