1. 程式人生 > >Go實戰--實現一個簡單的tcp服務端和客戶端(The way to go)

Go實戰--實現一個簡單的tcp服務端和客戶端(The way to go)

生命不止,繼續 go go go !!!

之前介紹了go為我們提供的net/http包,很方便的建立一些api。

今天就來點實戰,寫一個簡單的tcp的服務端、客戶端程式。

按照國際慣例,還是先介紹一點點基礎知識。

* net.Listen*
Listen announces on the local network address laddr. The network net must be a stream-oriented network: “tcp”, “tcp4”, “tcp6”, “unix” or “unixpacket”. For TCP and UDP, the syntax of laddr is “host:port”, like “127.0.0.1:8080”. If host is omitted, as in “:8080”, Listen listens on all available interfaces instead of just the interface with the given host address. See Dial for more details about address syntax.

Listening on a hostname is not recommended because this creates a socket for at most one of its IP addresses.

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

所以我們的server端就可以這麼寫:

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

bufio.NewReader
NewReader returns a new Reader whose buffer has the default size.

func NewReader(rd io.Reader) *Reader

Write

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

Write implements the Conn Write method.

net.Dial

func (d *Dialer) Dial(network, address string) (Conn, error)

Dial connects to the address on the named network.

See func Dial for a description of the network and address parameters.

基礎知識介紹差不多了,下面我們開始寫程式碼了。
tcp_server.go

package main

import "net"
import "fmt"
import "bufio"
import "strings" 

func main() {

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

    // listen on all interfaces
    ln, _ := net.Listen("tcp", "localhost: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"))
    }
}

tcp_client.go

package main

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

func main() {

    // connect to this socket
    conn, _ := net.Dial("tcp", "localhost: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)
    }
}

這裡寫圖片描述