日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

nc 模拟服务器_Go实战——实现一个并发时钟服务器

發布時間:2025/4/5 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 nc 模拟服务器_Go实战——实现一个并发时钟服务器 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

golang就是為高并發而生的,為我們提供了goroutines和channel。雖然前面博客的代碼片段中也有用到這兩個關鍵字,但是一直沒有組織好語言,也沒有能力把goroutines和channel寫好,那么估計我們先用,然后再看看的理解。

goroutines
A goroutine is a lightweight thread managed by the Go runtime.
幾個關鍵字:輕量級,線程。

package mainimport ( "fmt" "time")func say(s string) { for i := 0; i < 5; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(s) }}func main() { go say("world") say("hello")}

區別:

f() // call f(); wait for it to return go f() // create a new goroutine that calls f(); don't wait12

channels
Channels are the pipes that connect concurrent goroutines.
幾個關鍵字:管道 連接。

package mainimport "fmt"func main() { messages := make(chan string) go func() { messages

用了make聲明,時引用類型。

順序時鐘服務器
之前的博客已經介紹了很多,如何使用net/http包來構建一個服務器,關于golang中time package在昨天的博客中也有介紹了。
TCP 服務器,直接上代碼:

package mainimport ( "io" "log" "net" "time")func main() { listener, err := net.Listen("tcp", "localhost:8080") if err != nil { log.Fatal(err) } for { conn, err := listener.Accept() if err != nil { log.Print(err) continue } handleConn(conn) }}func handleConn(c net.Conn) { defer c.Close() for { _, err := io.WriteString(c, time.Now().Format("2006-01-02 15:04:05")) if err != nil { return } time.Sleep(1 * time.Second) }}

然后go build即可。

nc命令介紹
centos上安裝nc命令:

yum install nmap-ncat.x86_641

作用:
(1)實現任意TCP/UDP端口的偵聽,nc可以作為server以TCP或UDP方式偵聽指定端口
(2)端口的掃描,nc可以作為client發起TCP或UDP連接
(3)機器之間傳輸文件
(4)機器之間網絡測速

使用nc命令模擬client獲得服務器時間
后臺運行服務器:

./clock &1

使用nc命令:

nc localhost 80801

輸出結果:
2017-06-22 13:28:41
2017-06-22 13:28:42
2017-06-22 13:28:43
2017-06-22 13:28:44
2017-06-22 13:28:45
2017-06-22 13:28:46
2017-06-22 13:28:47
2017-06-22 13:28:48
2017-06-22 13:28:49
2017-06-22 13:28:50
2017-06-22 13:28:51
….

這是個順序服務器,如果多個客戶端連接的話,需要第一個結束后再執行第二個。

支持并發的始終服務器
很簡單,在上面的代碼在handle中加入關鍵字go即可:

package mainimport ( "io" "log" "net" "time")func main() { listener, err := net.Listen("tcp", "localhost:8080") if err != nil { log.Fatal(err) } for { conn, err := listener.Accept() if err != nil { log.Print(err) continue } go handleConn(conn) }}func handleConn(c net.Conn) { defer c.Close() for { _, err := io.WriteString(c, time.Now().Format("2006-01-02 15:04:05")) if err != nil { return } time.Sleep(1 * time.Second) }}

運行結果:

總結

以上是生活随笔為你收集整理的nc 模拟服务器_Go实战——实现一个并发时钟服务器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。