美文网首页
go 基础网络连接 socket

go 基础网络连接 socket

作者: 胡修波 | 来源:发表于2023-12-29 11:22 被阅读0次

    一、server端

    package main
    
    import (
        "bufio"
        "fmt"
        "net"
    )
    
    func main() {
        listen, err := net.Listen("tcp", "192.168.0.113: 20000")
        if err != nil {
            fmt.Println("listen failed, err: ", err)
            return
        }
        for {
            connect, err := listen.Accept()
            if err != nil {
                fmt.Println("accept failed err: ", err)
                continue
            }
            go process(connect)
        }
    }
    
    func process(connect net.Conn) {
        defer connect.Close()
        for {
            reader := bufio.NewReader(connect)
            var buf [128]byte
            n, err := reader.Read(buf[:])
            if err != nil {
                fmt.Println("read from client failed , err : ", err)
                break
            }
            recvStr := "form server: " + string(buf[:n])
            fmt.Println("收到client端发来的数据: ", recvStr)
            connect.Write([]byte(recvStr))
    
        }
    }
    
    

    二 client

    package main
    
    import (
        "bufio"
        "fmt"
        "net"
        "os"
        "strings"
    )
    
    func main() {
        conn, err := net.Dial("tcp", "192.168.0.113: 20000")
        if err != nil {
            fmt.Println("err: ", err)
            return
        }
    
        defer conn.Close()
    
        inputReader := bufio.NewReader(os.Stdin)
        for {
            intput, _ := inputReader.ReadString('\n')
            inputInfo := strings.Trim(intput, "\r\n")
            if strings.ToUpper(inputInfo) == "Q" {
                return
            }
            _, err := conn.Write([]byte(inputInfo))
            if err != nil {
                return
            }
            buf := [512]byte{}
            n, err := conn.Read(buf[:])
            if err != nil {
                fmt.Println("recv failed, err: ", err)
                return
            }
            fmt.Println(string(buf[:n]))
        }
    }
    
    

    相关文章

      网友评论

          本文标题:go 基础网络连接 socket

          本文链接:https://www.haomeiwen.com/subject/wrojndtx.html