zoukankan      html  css  js  c++  java
  • [转] golang socket

    server.go

    package main
    
    import (
        "net"
        "fmt"
        "io/ioutil"
        "time"
    )
    
    func main(){
        tcpServer, _ := net.ResolveTCPAddr("tcp4", ":8080")
        listener, _ := net.ListenTCP("tcp", tcpServer)
    
        for {
            conn, err := listener.Accept()
            if err != nil {
                fmt.Println(err)
                continue
            }
            // handle
            go handle(conn)
        }
    }
    
    func handle(conn net.Conn){
        defer conn.Close()
    
        //read msg from client
        go func(){
            response, _ := ioutil.ReadAll(conn)
            fmt.Println(response)
        }()
    
        // send msg to client
        time.Sleep(1 * time.Second)
        now := time.Now().String()
        conn.Write([]byte(now))
    }

    client.go

    package main
    
    import (
        "os"
        "fmt"
        "net"
        "io/ioutil"
    )
    
    func main()  {
        if len(os.Args) < 2 {
            fmt.Fprintf(os.Stderr, "Usage: %s host:port", os.Args[0])
        }
        // get socket addr from ags
        server := os.Args[1]
        addr, err := net.ResolveTCPAddr("tcp4", server)
        checkError(err)
    
        // establish conn
        conn, err := net.DialTCP("tcp4", nil, addr)
        checkError(err)
    
        // send msg to server
        _, err = conn.Write([]byte("HEAD / HTTP/1.0
    
    "))
        checkError(err)
    
        //get response
        response, _ := ioutil.ReadAll(conn)
        fmt.Println(string(response))
        os.Exit(0)
    }
    
    func checkError(err error){
        if err != nil{
            fmt.Println(err)
            os.Exit(1)
        }
    }

    原文:https://studygolang.com/articles/11796

  • 相关阅读:
    Edge 修改使用的默认搜索引擎
    VSCode 插件之
    Visual Studio Code 插件之
    一个随笔
    COGS 2479 偏序 题解
    [NOIP2015] 子串substring 题解
    [CQOI2011]动态逆序对
    树套树三题 题解
    一个随笔
    HEOI 2016 游记
  • 原文地址:https://www.cnblogs.com/dannyyao/p/7988420.html
Copyright © 2011-2022 走看看