1 client.go

  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "net"
  6. )
  7. type Client struct {
  8. ServerIp string
  9. ServerPort int
  10. Name string
  11. conn net.Conn
  12. flag int
  13. }
  14. func NewClient(serverIp string, serverPort int) *Client {
  15. // 创建客户端对象
  16. client := &Client{
  17. ServerIp: serverIp,
  18. ServerPort: serverPort,
  19. flag: 999,
  20. }
  21. // 连接server
  22. conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
  23. if err != nil {
  24. fmt.Println("net.Dial err:", err)
  25. return nil
  26. }
  27. client.conn = conn
  28. return client
  29. }
  30. func (this *Client) menu() bool {
  31. var flag int
  32. fmt.Println("1.公聊模式")
  33. fmt.Println("2.私聊模式")
  34. fmt.Println("3.更新用户名")
  35. fmt.Println("0.退出")
  36. fmt.Scanln(&flag) // 读取用户输入
  37. if flag >= 0 && flag <= 3 {
  38. this.flag = flag
  39. return true
  40. } else {
  41. fmt.Println("请输入0,1,2,3")
  42. return false
  43. }
  44. }
  45. func (this *Client) Run() {
  46. for this.flag != 0 {
  47. for !this.menu() {}
  48. switch this.flag {
  49. case 1:
  50. fmt.Println("已选择公聊模式")
  51. break
  52. case 2:
  53. fmt.Println("已选择私聊模式")
  54. break
  55. case 3:
  56. fmt.Println("更新用户名")
  57. break
  58. }
  59. }
  60. }
  61. var serverIp string
  62. var serverPort int
  63. // 此函数会在main函数之前被自动运行, client -i 127.0.0.1 -p 8888
  64. func init() {
  65. flag.StringVar(&serverIp, "i", "127.0.0.1", "设置服务器的IP地址(默认是127.0.0.1)")
  66. flag.IntVar(&serverPort, "p", 8888, "设置服务器的端口号(默认是8888)")
  67. flag.Parse() // 命令行解析
  68. }
  69. func main() {
  70. client := NewClient(serverIp, serverPort)
  71. if client == nil {
  72. fmt.Println("连接服务器失败")
  73. return
  74. }
  75. fmt.Println("连接服务器成功")
  76. client.Run()
  77. }