ARTS-S golang goroutines and channels(一)

First with golang implement a simple tcp server, assuming that a file named clock1.go

// clock1.go
package main

import (
    "fmt"
    "io"
    "net"
    "time"
)

func handleConn(c net.Conn) {
    defer c.Close()
    for {
        n, err := io.WriteString(c, time.Now().Format("15:04:05\n"))
        fmt.Println(n)
        if err != nil {
            return
        }
        time.Sleep(1 * time.Second)
    }
}

func main() {
    listen, err := net.Listen("tcp", "localhost:8080")
    if err != nil {
        fmt.Println(err)
    }
    for {
        conn, err := listen.Accept()
        if err != nil {
            fmt.Println(err)
            continue
        }
        handleConn(conn)
    }
}

Use the following command to compile and run

go build -o clock1
./clock1

It runs under mac or linux

nc locahost 8080

nc is the tool under linux. .clock1 corresponds tcp client after receiving the request, outputs the current time to the client.
Clock1 although able to display the current time, but there is a problem when the process is running in a nc locahost 8080 , then open a terminal, then execution will be stuck .clock1 nc locahost 8080 is an input terminal of a single-threaded
, handle only a client's request. clock2 below solves this problem by goroutinesq.

//clock2.go
package main

import (
    "fmt"
    "io"
    "net"
    "time"
)

func handleConn(c net.Conn)  {
    defer c.Close()
    for {
        _, err := io.WriteString(c, time.Now().Format("15:04:05\n"))
        if err != nil {
            fmt.Printf("write error %v", err)
            break
        }
        time.Sleep(1 * time.Second)
    }
}
func main() {
    listen, err := net.Listen("tcp", "localhost:8080")
    if err != nil {
        fmt.Println(err)
        return
    }
    for {
        conn, err := listen.Accept()
        if err != nil {
            fmt.Println(err)
            continue
        }
        go handleConn(conn)
    }
}

clock1.go and clock2.go difference is clock2.go of handleConn one more go, the equivalent of starting a new coroutine. Here the difference is not in-depth discussion threads and assistance, to mention only the most basic content.
First is the thread operating system implementation, coroutine is based on the thread, golang own implementation of a function. for programmers, can be simply understood as threads and coroutines are made to address asynchronous programming, thread by the operating
system for implementing the Association Cheng realized by programming language.

Guess you like

Origin www.cnblogs.com/zhouyang209117/p/11610105.html