[GO]tcp网络通信和实现

服务端的代码

package main

import (
    "net"
    "fmt"
)

func main() {
    //监听
    listener, err := net.Listen("tcp", ":8000") //不写IP地址代表监听的是本机
    if err != nil {
        fmt.Println("listener errinfo = ", err)
        return
    }
    defer listener.Close()

    conn,err := listener.Accept()//阻塞,等待用户连接
    if err != nil {
        fmt.Println("accept err = ", err)
        return
    }
    //接收用户的请求
    buf := make([]byte, 1024)
    n, err1 := conn.Read(buf)
    if err1 != nil{
        fmt.Println("err1 = ", err1)
        return
    }
    fmt.Println(" buf = ", string(buf[:n]))
    defer conn.Close() //关闭当前用户的连接
}

客户端的代码

package main

import (
    "net"
    "fmt"
)

func main() {
    //主动连接服务器
    conn, err:=net.Dial("tcp", "127.0.0.1:8000")
    if err != nil {
        fmt.Println("err = ", err)
        return
    }
    defer conn.Close()

    conn.Write([]byte("are you ok"))
}

 它们的实现步骤为

posted @ 2018-09-20 14:57  蟒城贝勒爷  阅读(148)  评论(0编辑  收藏  举报