Socket程序示例1
Server
package mainimport (
"io"
"log"
"net"
"time"
)func main() {
listener, err := net.Listen("tcp", "localhost:8000")
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, "hello... \n")
if err != nil {
return
}
time.Sleep(1 * time.Second)
}
}
Client
package mainimport (
"io"
"log"
"net"
"os"
)func main() {
conn, err := net.Dial("tcp", "localhost:8000")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
supposedCopy(os.Stdout, conn)
}func supposedCopy(dst io.Writer, src io.Reader) {
if _, err := io.Copy(dst, src);
err != nil {
log.Fatal(err)
}
}
程序运行
控制台分别运行命令
go run tryTimeServer.go
go run tryTimeClient.go
运行效果
运行效果如下图所示
文章图片
Socket程序示例2 tryTimeServer.go
package mainimport (
"io"
"log"
"net"
"time"
)func main() {
listener, err := net.Listen("tcp", "localhost:8000")
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\r\n"))
//_, err1 := io.WriteString(c, timestr + "hello... \n")
if err != nil {
return
}
time.Sleep(1 * time.Second)
}
}
tryTimeClient.go
package mainimport (
"io"
"log"
"net"
"os"
)func main() {
conn, err := net.Dial("tcp", "localhost:8000")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
supposedCopy(os.Stdout, conn)
}func supposedCopy(dst io.Writer, src io.Reader) {
if _, err := io.Copy(dst, src);
err != nil {
log.Fatal(err)
}
}
运行效果
【Golang网络编程-Socket】
文章图片
推荐阅读
- 【golang】leetcode中级-字母异位词分组&无重复字符的最长子串
- 彻底理解Golang Map
- kratos线上开源年会它来啦~
- 深入浅出 Golang 资源嵌入方案(go-bindata篇)
- 深入浅出 Golang 资源嵌入方案(前篇)
- golang 经典案例总结
- Go实战 | 基于有向无环图的并发执行流的实现
- Golang 数组和切片
- Go JSON编码与解码()
- golang map基础知识