一段Go语言实现的socket 测试代码
用golang不用他的net包还有什么意义,又一个测试代码.
server.go 服务端
package main import ( "fmt" "log" "net" "bufio" ) func handleConnection(conn net.Conn) { data, err := bufio.NewReader(conn).ReadString('\n') if err != nil { log.Fatal("get client data error: ", err) } fmt.Printf("%#v\n", data) fmt.Fprintf(conn, "hello client\n") conn.Close() } func main() { ln, err := net.Listen("tcp", ":6010") if err != nil { panic(err) } for { conn, err := ln.Accept() if err != nil { log.Fatal("get client connection error: ", err) } go handleConnection(conn) } }
client.go 客户端
package main import ( "fmt" "net" "bufio" ) func main() { conn, err := net.Dial("tcp", ":6010") if err != nil { panic(err) } fmt.Fprintf(conn, "hello server\n") data, err := bufio.NewReader(conn).ReadString('\n') if err != nil { panic(err) } fmt.Printf("%#v\n", data) }