golang使用net库实现一个简单的服务端和客户端通信

版权声明:http://blog.csdn.net/robertkun https://blog.csdn.net/robertkun/article/details/79162868

golang使用net库实现一个简单的服务端和客户端通信

服务端代码:
服务端启动监听,默认127.0.0.1, 设置端口9090

package main

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

func recvFile(conn net.Conn) {
    fmt.Println("new connection: ", conn.RemoteAddr())
    defer conn.Close()
}

func main() {
    var (
        port = "9090"
        remote = ":" + port
    )
    fmt.Println(remote)

    lisn, err := net.Listen("tcp", remote)
        defer lisn.Close()

    if err != nil {
        fmt.Println("server listen failed!", err)
        os.Exit(-1)
    }

    for {
        conn, err := lisn.Accept()
        if err != nil {
            fmt.Println("client connect failed!", err)
            continue
        }

        go recvFile(conn)
    }
}

客户端代码:
客户端发起连接,目标ip127.0.0.1, 端口:9090

package main

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

func main() {
    var (
        host   = "127.0.0.1"
        port   = "9090"
        remote = host + ":" + port
    )

    fmt.Println(remote)
    conn, err := net.Dial("tcp", remote)
    defer conn.Close()

    if err != nil {
        fmt.Println("connect server failed!.")
        os.Exit(-1)
        return
    }

    fmt.Println(0, "connect ok! sending file...")
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页