/**************搜索已添加的好友**************/ private void Searchfrdbtn_Click(object sender, EventArgs e) { string friendID = FrdIDbox.Text; //先判断输入是否为有效ID bool validfriendID = true; if (friendID.Length == 10) { for (int i = 0; i < 10; i++) { if ((friendID[i] - '0') < 0 || (friendID[i] - '0' > 9)) { validfriendID = false; break; } } } else { validfriendID = false; } if (!validfriendID) //若ID无效 { MessageBox.Show("请输入有效的ID(10位数字)"); FrdIDbox.Clear(); //清除 return; } //在friendlistbox查找这个ID,并选中 for (int i = 0; i < friendListBox.Items.Count; i++) { if ((friendListBox.Items[i] as string).Contains(friendID)) { friendListBox.SelectedIndex = i; friendListBox.TopIndex = i; return; } } if (friendID == userID) { MessageBox.Show("请不要搜索自己"); return; } //若没有查找到这个ID MessageBox.Show(friendID + "还不是你的好友"); }
/**************添加新朋友*****************/ private void Addfrdbtn_Click(object sender, EventArgs e) { string friendID = FrdIDbox.Text; //先判断输入是否为有效ID bool validfriendID = true; if (friendID.Length == 10) { for (int i = 0; i < 10; i++) { if ((friendID[i] - '0') < 0 || (friendID[i] - '0' > 9)) { validfriendID = false; break; } } } else { validfriendID = false; } if (!validfriendID) //若ID无效 { MessageBox.Show("请输入有效的ID(10位数字)"); FrdIDbox.Clear(); //清除 return; } //检查friendlistbox是否已添加该好友 for (int i = 0; i < friendListBox.Items.Count; i++) { if ((friendListBox.Items[i] as string).Contains(friendID)) { MessageBox.Show(friendID + "已经是你的好友"); return; } } if (friendID == userID) { MessageBox.Show("请不要添加自己"); return; } //否则,先向服务器查询对方状态,获得IP string sendMsg = "q" + friendID; byte[] sendByt = Encoding.ASCII.GetBytes(sendMsg); //NetworkStream toServerStream = toServer.GetStream(); toServerStream.Write(sendByt, 0, sendByt.Length); byte[] rcvByt = new byte[1024]; int rcvLength = toServerStream.Read(rcvByt, 0, rcvByt.Length); string rcvMsg = Encoding.ASCII.GetString(rcvByt, 0, rcvLength); //toServerStream.Close(); if (rcvMsg == "n") { MessageBox.Show(friendID + "已离线,请稍后添加"); } else { //再向friendID发送好友请求rff TcpClient tcptoFriend = new TcpClient(); tcptoFriend.Connect(rcvMsg, listenPort); NetworkStream streamtoFriend = tcptoFriend.GetStream(); sendMsg = "rff" + userID; sendByt = Encoding.Unicode.GetBytes(sendMsg); streamtoFriend.Write(sendByt, 0, sendByt.Length); streamtoFriend.Close(); tcptoFriend.Close(); MessageBox.Show("已向" + friendID + "发送好友申请"); } }