go简单的socket编程

服务端

package main

import (
    "bufio"
    "fmt"
    "net"
    "os"
    "strings"
)

func process(conn net.Conn){
    var buffer [128]byte

    //这个循环的目的是,如果客户端发来的数据过长,将数据切片
    for{
        m,err := conn.Read(buffer[:])
        if err != nil{
            fmt.Println("read data failed")
            break
        }
        fmt.Println("客户端发来的数据是:",string(buffer[:m]))

        reader := bufio.NewReader(os.Stdin)
        fmt.Print("请输入服务端发送的数据:")
        sendinfo,err := reader.ReadString('\n')
        if err != nil{
            fmt.Println("读取服务端发送数据出错!")
            continue
        }
        sendinfo = strings.TrimSpace(sendinfo)
        if sendinfo == "exit"{
            fmt.Println("退出服务端")
            return
        }
        conn.Write([]byte(sendinfo))
    }
}

func main(){
    listener,err := net.Listen("tcp","127.0.0.1:9100")
    if err != nil{
        fmt.Println("start server 9100 failed")
        return
    }
    fmt.Println("start server 9100 success")

    for {
        conn,err := listener.Accept()
        if err != nil{
            fmt.Println("accept server fail")
            return
        }
        fmt.Println("accept server success")    //客户端连接成功打印此日志
        go process(conn)
    }
}

客户端

package main

import (
    "bufio"
    "fmt"
    "net"
    "os"
    "strings"
)

func main(){
    conn,err := net.Dial("tcp","127.0.0.1:9100")
    if err != nil{
        fmt.Println("connect server 9100 fail")
        return
    }
    fmt.Println("connect server 9100 success")

    reader := bufio.NewReader(os.Stdin)
    for{
        fmt.Print("请输入:")
        msg,_:=reader.ReadString('\n')
        msg=strings.TrimSpace(msg)
        if msg == "exit"{
            fmt.Println("exit client")
            return
        }
        conn.Write([]byte(msg))

        var buffer [128]byte
        for{
            n,err := conn.Read(buffer[:])
            if err != nil{
                fmt.Println("客户端读取数据出错")
                break
            }
            fmt.Println("客户端读取数据是:",string(buffer[:n]))
            break
        }

    }
}

你可能感兴趣的:(go简单的socket编程)