46 lines
770 B
Go
46 lines
770 B
Go
// 客户端应用
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"time"
|
|
)
|
|
|
|
type Client struct {
|
|
ServerIp string
|
|
ServerPort int
|
|
Name string
|
|
conn net.Conn
|
|
}
|
|
|
|
func NewClient(serverIp string, serverPort int) *Client {
|
|
// 创建Client对象
|
|
client := &Client{
|
|
ServerIp: serverIp,
|
|
ServerPort: serverPort,
|
|
}
|
|
// 连接Server
|
|
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
|
|
if err != nil {
|
|
fmt.Println("net.Dial err:", err)
|
|
return nil
|
|
}
|
|
client.conn = conn
|
|
// 返回Client对象
|
|
return client
|
|
}
|
|
|
|
func main() {
|
|
client := NewClient("127.0.0.1", 8888)
|
|
if client == nil {
|
|
fmt.Println(">>>>>> 连接服务器失败!")
|
|
return
|
|
}
|
|
fmt.Println(">>>>>> 连接服务器成功……")
|
|
|
|
for {
|
|
time.Sleep(1 * time.Second)
|
|
}
|
|
}
|