golang tcp server client

前端之家收集整理的这篇文章主要介绍了golang tcp server client前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

实例代码如下:

server

import (
        "fmt"
        "net"
        "log"
)

func main() {

        addr := "0.0.0.0:8080"

        tcpAddr,err := net.ResolveTCPAddr("tcp",addr)

        if err != nil {
                log.Fatalf("net.ResovleTCPAddr fail:%s",addr)
        }

        listener,err := net.ListenTCP("tcp",tcpAddr)
        if err != nil {
                log.Fatalf("listen %s fail: %s",addr,err)
        } else {

                log.Println("rpc listening",addr)
        }


        for {
                conn,err := listener.Accept()
                if err != nil {
                        log.Println("listener.Accept error:",err)
                        continue
                }

                go handleConnection(conn)

        }

}


func handleConnection(conn net.Conn) {

        defer conn.Close()

        var buffer []byte = []byte("You are welcome. I'm server.")

        n,err := conn.Write(buffer)

        if err != nil {

                fmt.Println("Write error:",err)
        }
        fmt.Println("send:",n)

        fmt.Println("connetion end")

}

client

package main


import (
        "fmt"
        "net"
        "os"
)

func main() {

        conn,err := net.Dial("tcp","127.0.0.1:8080")
        if err != nil {
                fmt.Println("dial Failed:",err)
                os.Exit(1)
        }
        defer conn.Close()


        buffer := make([]byte, 512)

        n,err2 := conn.Read(buffer)
        if err2 != nil {
                fmt.Println("Read Failed:",err2)
                return
        }

        fmt.Println("count:",n,"msg:",string(buffer))


}

Read函数最多读取len(buffer)个字节到buffer中。

测试

server output:

2017/10/05 00:12:18 rpc listening 0.0.0.0:8080
send: 28
connetion end

client output:

count: 28 msg: You are welcome. I’m server.

原文链接:https://www.f2er.com/go/187878.html

猜你在找的Go相关文章