private void button2_Click(object sender, EventArgs e)//点击"退出登录"按键,执行下线功能 { InfoWindow Confirm = new InfoWindow("确认退出当前账号?", true); Confirm.StartPosition = FormStartPosition.CenterParent; Confirm.ShowDialog(); if (Confirm.DialogResult == DialogResult.OK)//确认退出 { Confirm.Close(); TcpClient client = new TcpClient(); try { client.Connect(BasicInfo.ServerIp, BasicInfo.ServerPort); } catch { InfoWindow Mes = new InfoWindow("服务器正忙\n 请稍等", false); Mes.StartPosition = FormStartPosition.CenterParent; Mes.Show(); return; } if (client.Connected)//连接成功发送下线请求 { NetworkStream ClientToServer = client.GetStream(); string LoginInfo = "logout" + BasicInfo.UserName; //"logout"+学号 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 == "loo")//服务器返回成功下线信息 { ClientToServer.Close(); client.Close(); InfoWindow Mes = new InfoWindow("下线成功!", false); Mes.StartPosition = FormStartPosition.CenterParent; Mes.ShowDialog(); if (Mes.DialogResult == DialogResult.Cancel) { System.Environment.Exit(0);//关闭所有进程 } } else { //InfoWindow Mes = new InfoWindow("服务器状态异常\n 请稍等", false);//提示信息好像会重复,这里不要了 //Mes.StartPosition = FormStartPosition.CenterParent; //Mes.Show(); return; } } } }
static void Logout()//下线功能,现已移植到ChatWindow中 { InfoWindow Confirm = new InfoWindow("确认退出当前账号?", true); Confirm.StartPosition = FormStartPosition.CenterParent; Confirm.ShowDialog(); if (Confirm.DialogResult == DialogResult.OK) { Confirm.Close(); TcpClient client = new TcpClient(); try { client.Connect(BasicInfo.ServerIp, BasicInfo.ServerPort); } catch { InfoWindow Mes = new InfoWindow("服务器无响应\n您已强制退出程序", false); Mes.StartPosition = FormStartPosition.CenterParent; Mes.Show(); } if (client.Connected) { NetworkStream ClientToServer = client.GetStream(); string LoginInfo = "logout" + BasicInfo.UserName; //下线格式:"logout"+学号 byte[] send = Encoding.Default.GetBytes(LoginInfo); //将输入信息转化为byte字节流 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 == "loo") { ClientToServer.Close(); client.Close(); InfoWindow Mes = new InfoWindow("您已强制退出程序\n 下线成功!", false); Mes.StartPosition = FormStartPosition.CenterParent; Mes.ShowDialog(); if (Mes.DialogResult == DialogResult.Cancel) { System.Environment.Exit(0); } //关闭所有进程 } else { InfoWindow Mes = new InfoWindow("未成功下线!\n您已强制退出程序", false); Mes.StartPosition = FormStartPosition.CenterParent; Mes.Show(); } } } }