其他分享
首页 > 其他分享> > go 及时通信-命令行解析

go 及时通信-命令行解析

作者:互联网

package main

import (
	"flag"
	"fmt"
	"net"
)

type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	Conn       net.Conn
}

func NewClient(serverIp string, serverPort int) *Client {
	client := &Client{
		ServerIp:   serverIp,
		ServerPort: serverPort,
	}

	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

	return client
}

var ServerIp string
var ServerPort int

func init() {
	flag.StringVar(&ServerIp, "ip", "127.0.0.1", "设置服务器的IP地址(默认127.0.0.1)")
	flag.IntVar(&ServerPort, "port", 7777, "设置服务器的端口(默认7777)")
}

func main() {
	//命令行解析
	flag.Parse()

	client := NewClient(ServerIp, ServerPort)

	if client == nil {
		fmt.Println("<========连接失败")
		return
	}

	fmt.Println("<=========连接成功")

	select {}
}

  

标签:ServerPort,ServerIp,flag,client,命令行,go,net,解析,string
来源: https://www.cnblogs.com/alway-learn/p/16106033.html