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

标签: go语言net
4449人阅读 评论(0) 收藏 举报
分类:

生命不止,继续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)
这里写图片描述

1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4343559次
    • 积分:39570
    • 等级:
    • 排名:第110名
    • 原创:559篇
    • 转载:28篇
    • 译文:13篇
    • 评论:749条
    微信公众号
      我的微信公众号
      为你推荐最新的博文~更有惊喜等着你
    时光荏苒
      白驹过隙
    博客专栏
    文章分类
    百度统计
    Google Analytics