Example #1
0
        private void LoginButton_Click(object sender, EventArgs e)
        {
            string LoginInfo;
            int    Port = 10000;

            try//记录端口
            {
                Port = int.Parse(NameText.Text.Substring(6)) + 10000;
            }
            catch
            {
                InfoWindow Mes = new InfoWindow("请输入有效账号", false);
                Mes.StartPosition = FormStartPosition.CenterParent;
                Mes.ShowDialog();
            }
            IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();

            IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();

            foreach (IPEndPoint endPoint in ipEndPoints)//判断该端口是否被占用
            {
                if (endPoint.Port == Port)
                {
                    InfoWindow Mes = new InfoWindow("该账号已登录", false);
                    Mes.StartPosition = FormStartPosition.CenterParent;
                    Mes.ShowDialog();
                    return;
                }
            }
            TcpClient client = new TcpClient();

            try//尝试连接服务器
            {
                client.Connect(BasicInfo.ServerIp, BasicInfo.ServerPort);
            }
            catch//未连接成功
            {
                InfoWindow Mes = new InfoWindow("连接失败\n请稍后重试", false);
                Mes.StartPosition = FormStartPosition.CenterParent;
                Mes.ShowDialog();
            }
            if (client.Connected)
            {
                NetworkStream ClientToServer = client.GetStream();
                LoginInfo = NameText.Text + "_" + PasswordText.Text;
                byte[] send = Encoding.Default.GetBytes(LoginInfo); //将输入信息转化为字节流
                ClientToServer.Write(send, 0, send.Length);         //写入NetworkStream

                //接收
                byte[] msg      = new byte[1024];
                int    length   = ClientToServer.Read(msg, 0, msg.Length);
                string response = Encoding.Default.GetString(msg, 0, length);
                Console.WriteLine(response);
                if (response == "lol")//服务器返回登录成功
                {
                    BasicInfo.UserName = NameText.Text;
                    ClientToServer.Close();
                    client.Close();
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    InfoWindow Mes = new InfoWindow("用户名或密码错误!", false);
                    Mes.StartPosition = FormStartPosition.CenterParent;
                    Mes.ShowDialog();
                }
            }
            else
            {
                return;
            }
        }