欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

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

发布时间:2025/4/5 编程问答 33 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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实战——实现一个并发时钟服务器的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。