go tcp demo

package main

import (

"fmt"

"net"

_"io"

)

//建立函数建立协程

func process(conn net.Conn){

    defer conn.Close()

    for{

        buf := make([]byte ,1024)

        fmt.Printf("服务器等待客户端%s 发送消息 \n ",conn.RemoteAddr().String())

            n,err := conn.Read(buf)

                if err != nil {

                    fmt.Print("客户端退出")

                    return          //!!!

                }

            //显示客户端发送内容到服务器终端

            fmt.Print(string(buf[:n]))

    }


}

func main (){

    fmt.Println("服务器开启监听")

        listen,err :=net.Listen("tcp","0.0.0.0:8888")

            if err != nil{

                fmt.Printf("Filed to listen,the error is %v \n",err)

            }

        defer listen.Close()


        for{

            coon,err := listen.Accept()

                if err != nil{

                    fmt.Printf("连接失败 the error is %v \n",err)

                }else {

                    fmt.Printf("connect successful,coon is %v client IP is %v  \n",coon,coon.RemoteAddr().String())

                }

        go process(coon)


        }

}

你可能感兴趣的:(go tcp demo)