IM-System版本0.9.2让client可以接收命令行参数,实现客户端菜单

This commit is contained in:
wandoubaba 2024-11-27 15:15:47 +08:00
parent 93ce7310ba
commit 2cb4cd4120

View File

@ -2,9 +2,9 @@
package main
import (
"flag"
"fmt"
"net"
"time"
)
type Client struct {
@ -12,6 +12,7 @@ type Client struct {
ServerPort int
Name string
conn net.Conn
flag int // 当前client模式
}
func NewClient(serverIp string, serverPort int) *Client {
@ -19,6 +20,7 @@ func NewClient(serverIp string, serverPort int) *Client {
client := &Client{
ServerIp: serverIp,
ServerPort: serverPort,
flag: 999,
}
// 连接Server
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
@ -31,15 +33,70 @@ func NewClient(serverIp string, serverPort int) *Client {
return client
}
func (client *Client) menu() bool {
var flag int
fmt.Println("1. 公聊模式")
fmt.Println("2. 私聊模式")
fmt.Println("3. 更新用户名")
fmt.Println("0. 退出")
fmt.Scanln(&flag)
client.flag = flag
if flag >= 0 && flag <= 3 {
return true
} else {
fmt.Println(">>>>>> 请输入合法的数字 <<<<<<")
return false
}
}
func (client *Client) Run() {
for client.flag != 0 {
for !client.menu() {
}
// 根据不同的模式处理不同的业务
switch client.flag {
case 1:
// 公聊模式
fmt.Println("已选择公聊模式...")
case 2:
// 私聊模式
fmt.Println("已选择私聊模式...")
case 3:
// 更新用户名
fmt.Println("已选择更新用户名模式...")
}
}
}
// 定义全局变量
var serverIp string
// 定义全局变量
var serverPort int
// init函数会在main函数之前执行
func init() {
// ./client -ip 127.0.0.1
flag.StringVar(&serverIp, "ip", "127.0.0.1", "设置服务端IP地址默认127.0.0.1")
// ./client -port 8888
flag.IntVar(&serverPort, "port", 8888, "设置服务端端口默认8888")
}
func main() {
client := NewClient("127.0.0.1", 8888)
// 解析命令行传参
flag.Parse()
client := NewClient(serverIp, serverPort)
if client == nil {
fmt.Println(">>>>>> 连接服务器失败!")
return
}
fmt.Println(">>>>>> 连接服务器成功……")
for {
time.Sleep(1 * time.Second)
}
// for {
// time.Sleep(1 * time.Second)
// }
client.Run()
}