Golang网络编程-Socket

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

运行效果
运行效果如下图所示
Golang网络编程-Socket
文章图片

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网络编程-Socket
文章图片

    推荐阅读