Go语言 之Socket简单C/S模型通信
服务端:
package main import ( "fmt" "net" ) func main() { listen, err := net.Listen("tcp", ":8000") if err != nil { fmt.Println(err.Error()) return } defer listen.Close() fmt.Println("等待客户端连接") conn, err := listen.Accept() if err != nil { fmt.Println(err.Error()) return } defer conn.Close() //读取数据 fmt.Println("开始读取数据") b := make([]byte, 1024) n, _ := conn.Read(b) fmt.Println(conn.RemoteAddr().String() + ": 读到的数据为" + string(b[:n])) }
Listen函数:
func Listen(network, address string) (Listener, error)
network:选用的协议:TCP、UDP, 如:“tcp”或 “udp”
address:IP地址+端口号, 如:“127.0.0.1:8000”或 “:8000”
Listener 接口:
type Listener interface {
Accept() (Conn, error)
Close() error
Addr() Addr
}
Conn 接口:
type Conn interface {
Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
Close() error
LocalAddr() Addr
RemoteAddr() Addr
SetDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error
}
客户端:
package main import ( "fmt" "net" ) func main() { //创建客户端 listen, err := net.Dial("tcp", ":8000") if err != nil { fmt.Println(err.Error()) return } defer listen.Close() var str string = "haha" buf := []byte(str) listen.Write(buf) }
Dial函数:
func Dial(network, address string) (Conn, error)
network:选用的协议:TCP、UDP,如:“tcp”或 “udp”
address:服务器IP地址+端口号, 如:“121.36.108.11:8000”或 “www.itcast.cn:8000”
Conn 接口:
type Conn interface {
Read(b []byte) (n int, err error)
Write(b []byte) (n int, err error)
Close() error
LocalAddr() Addr
RemoteAddr() Addr
SetDeadline(t time.Time) error
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error
}