zoukankan      html  css  js  c++  java
  • Go语言TCP/UDP Socket编程

    1. TCP编程

    TCPClient

    // TCPClient project main.go
    package main
    
    import (
        "fmt"
        "net"
        "os"
    )
    
    func main() {
        var buf [512]byte
        if len(os.Args) != 2 {
            fmt.Fprintf(os.Stderr, "Usage: %s host:port ", os.Args[0])
            os.Exit(1)
        }
        service := os.Args[1]
        tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
        checkErr(err)
        conn, err := net.DialTCP("tcp", nil, tcpAddr)
        defer conn.Close()
        checkErr(err)
        rAddr := conn.RemoteAddr()
        n, err := conn.Write([]byte("Hello server!"))
        checkErr(err)
        n, err = conn.Read(buf[0:])
        checkErr(err)
        fmt.Println("Reply from server ", rAddr.String(), string(buf[0:n]))
        os.Exit(0)
    }
    
    func checkErr(err error) {
        if err != nil {
            fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
            os.Exit(1)
        }
    }

    TCPServer

    // TCPServer project main.go
    package main
    
    import (
        "fmt"
        "net"
        "os"
    )
    
    func main() {
        service := ":5000"
        tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
        checkErr(err)
        listener, err := net.ListenTCP("tcp", tcpAddr)
        checkErr(err)
        for {
            conn, err := listener.Accept()
            if err != nil {
                continue
            }
            go handleClient(conn)
        }
    }
    
    func checkErr(err error) {
        if err != nil {
            fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
            os.Exit(1)
        }
    }
    
    func handleClient(conn net.Conn) {
        defer conn.Close()
        var buf [512]byte
        for {
            n, err := conn.Read(buf[0:])
            if err != nil {
                return
            }
            rAddr := conn.RemoteAddr()
            fmt.Println("Receive from client", rAddr.String(), string(buf[0:n]))
            _, err2 := conn.Write([]byte("Welcome client!"))
            if err2 != nil {
                return
            }
        }
    }

    2. UDP编程

    UPDClient

    // UDPClient project main.go
    package main
    
    import (
        "fmt"
        "net"
        "os"
    )
    
    func main() {
        var buf [512]byte
        if len(os.Args) != 2 {
            fmt.Fprintf(os.Stderr, "Usage: %s host:port ", os.Args[0])
            os.Exit(1)
        }
        service := os.Args[1]
        udpAddr, err := net.ResolveUDPAddr("udp4", service)
        checkErr(err)
        conn, err := net.DialUDP("udp", nil, udpAddr)
        defer conn.Close()
        checkErr(err)
        rAddr := conn.RemoteAddr()
        n, err := conn.Write([]byte("Hello server!"))
        checkErr(err)
        n, err = conn.Read(buf[0:])
        checkErr(err)
        fmt.Println("Reply from server ", rAddr.String(), string(buf[0:n]))
        os.Exit(0)
    }
    
    func checkErr(err error) {
        if err != nil {
            fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
            os.Exit(1)
        }
    }

    UDPServer

    // UDPServer project main.go
    package main
    
    import (
        "fmt"
        "net"
        "os"
    )
    
    func main() {
        service := ":5000"
        udpAddr, err := net.ResolveUDPAddr("udp4", service)
        checkErr(err)
        conn, err := net.ListenUDP("udp", udpAddr)
        checkErr(err)
        for {
            handleClient(conn)
        }
    }
    
    func checkErr(err error) {
        if err != nil {
            fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
            os.Exit(1)
        }
    }
    
    func handleClient(conn *net.UDPConn) {
        defer conn.Close()
        var buf [512]byte
        for {
            n, rAddr, err := conn.ReadFromUDP(buf[0:])
            if err != nil {
                return
            }
            fmt.Println("Receive from client", rAddr.String(), string(buf[0:n]))
            _, err2 := conn.WriteToUDP([]byte("Welcome client!"), rAddr)
            if err2 != nil {
                return
            }
        }
    }
  • 相关阅读:
    duilib框架分析:几个回调(C++11)
    duilib框架分析(一)概述
    图解JVM--(二)垃圾回收
    图解jvm--(一)jvm内存结构
    4 (计算机网络) DHCP与PXE:IP是怎么来的,又是怎么没的?
    3(计算机网络)ifconfig:最熟悉又陌生的命令行
    2 (计算机网络)理解网络协议的工作模式
    1 (计算机网络)我们常用的网络协议有哪些?
    阿里云配置mysql
    深入Spring Boot:那些注入不了的Spring占位符(${}表达式)
  • 原文地址:https://www.cnblogs.com/gaopeng527/p/6128290.html
Copyright © 2011-2022 走看看