Golang-socket

Golang-socket

socket

Client code

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
    }else {
        fmt.Println(conn.LocalAddr().String() + "Client connection is successful!")
    }

    defer conn.Close()
   //Send data to the server
    reader := bufio.NewReader(conn)
    conn.Write([]byte("hi server/n"))
    for {
       //Accept the data returned by the server
        msg, err := reader.ReadString('\n')
        fmt.Println(msg)
        if err != nil || err == io.EOF {
            fmt.Println(err)
            break
        }
        time.Sleep(time.2.* 2)

        b := []byte(fmt.Sprintf("client time:%s\n",time.Now().String()))
        _, err = conn.Write(b)

        if err != nil {
            fmt.Println(err)
            break
        }
    }
}

Server code

package main

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

//tcp server 

func main() {
   //Define a tcp breakpoint
    var tcpAddr *net.TCPAddr
   //A specific tcp breakpoint through the ResolveTCPAddr instance
    tcpAddr,_ = net.ResolveTCPAddr("tcp",":9999")
   //Open a tcp breakpoint monitor
    tcpListener,err:= net.ListenTCP("tcp",tcpAddr)
    if err !=nil{
        panic(err)
    }
    defer tcpListener.Close()
    fmt.Println("server start success")
   //Receive the client connection in a loop, and create a coroutine to handle the connection
    for{
        tcpConn,err := tcpListener.AcceptTCP()
        if err!=nil {
            fmt.Println(err)
            continue
        }
        fmt.Println(tcpConn.RemoteAddr().String()+"connect success")
        go tcpPipe(tcpConn)
    }
}

//Specifically handle the connection process method
func tcpPipe(conn *net.TCPConn){
   //tcp connection address
    ipStr := conn.RemoteAddr().String()

    defer func() {
        fmt.Println(" Disconnected: "+ ipStr)
        conn.Close()
    }()
   //Get a connected reader to read the stream
    reader := bufio.NewReader(conn)
    for {
        message,_,err := reader.ReadLine()
        if err!=nil || err == io.EOF {
            break
        }
        fmt.Println(string(message))

        time.Sleep(time.Second*3)
        
        b := []byte(fmt.Sprintf("server time:%s\n",time.Now().String()))

        conn.Write(b)
        
    }
}
Reference: https://cloud.tencent.com/developer/article/1438615 Golang——socket-Cloud + Community-Tencent Cloud