wangshubo1989的博客

一蓑烟雨任平生 也无风雨也无晴

Go语言学习之net包(The way to go)

生命不止,继续go go go!!!

不要问我net包和net/http包的区别,我们先会用,两者的区别慢慢去体会。

net包有什么作用?

Package net provides a portable interface for network I/O, including TCP/IP, UDP, domain name resolution, and Unix domain sockets.

Although the package provides access to low-level networking primitives, most clients will need only the basic interface provided by the Dial, Listen, and Accept functions and the associated Conn and Listener interfaces.

下面介绍几个方法

Dial
语法:

func Dial(network, address string) (Conn, error)

作用:Dial connects to the address on the named network.
例子:

Dial("tcp", "192.0.2.1:80")
Dial("tcp", "golang.org:http")
Dial("tcp", "[2001:db8::1]:http")
Dial("tcp", "[fe80::1%lo0]:80")
Dial("tcp", ":80")

Listen
语法:

func Listen(net, laddr string) (Listener, error)

作用:
Listen announces on the local network address laddr.

例子:

ln, _ := net.Listen("tcp", ":8081")

Accept
语法:

func (l *TCPListener) Accept() (Conn, error)

作用:
Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn.

例子:

conn, _ := ln.Accept()

Write
语法:

func (c *UnixConn) Write(b []byte) (int, error)

作用:
Write implements the Conn Write method.

例子:

conn.Write([]byte(newmessage + "\n"))

-------------------------------
下面,献上一个完整的例子,通过golang中的net包,实现一个tcp的server,client聊天的功能。

首先是server端:

package main

import "net"
import "fmt"
import "bufio"
import "strings" // only needed below for sample processing

func main() {

    fmt.Println("Launching server...")

    // listen on all interfaces
    ln, _ := net.Listen("tcp", ":8081")

    // accept connection on port
    conn, _ := ln.Accept()

    // run loop forever (or until ctrl-c)
    for {
        // will listen for message to process ending in newline (\n)
        message, _ := bufio.NewReader(conn).ReadString('\n')
        // output message received
        fmt.Print("Message Received:", string(message))
        // sample process for string received
        newmessage := strings.ToUpper(message)
        // send new string back to client
        conn.Write([]byte(newmessage + "\n"))
    }
}

其次是client端:

package main

import "net"
import "fmt"
import "bufio"
import "os"

func main() {

    // connect to this socket
    conn, _ := net.Dial("tcp", ":8081")
    for {
        // read in input from stdin
        reader := bufio.NewReader(os.Stdin)
        fmt.Print("Text to send: ")
        text, _ := reader.ReadString('\n')
        // send to socket
        fmt.Fprintf(conn, text + "\n")
        // listen for reply
        message, _ := bufio.NewReader(conn).ReadString('\n')
        fmt.Print("Message from server: "+message)
    }
}

这里面用到了bufio包,在后面的博客我们会做详细的介绍,请稍安勿躁。

还有:
func Fprintf(w io.Writer, format string, a …interface{}) (n int, err error)
这里写图片描述

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangshubo1989/article/details/70151852
文章标签: go语言 net
个人分类: go
所属专栏: Go从入门到不放弃
上一篇Go语言学习之net/http包(The way to go)
下一篇Go语言学习之bufio包(The way to go)
想对作者说点什么? 我来说一句

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

关闭
关闭