//得到好友列表 private void get_friend_list(bool flag) { if (listView1.InvokeRequired) { query_Friend d = new query_Friend(get_friend_list); this.Invoke(d, new object[] { false }); } else { //listView1.Clear(); if (friend_list != null) { string[] friend_array; friend_array = friend_list.Split('.'); for (int i = 0; i < friend_array.Length; i++) { string friend = friend_array[i]; string info = Server_Connection.Search_Friend(friend, client_socket); if (flag)//第一次刷新 { ListViewItem new_item = new ListViewItem(); new_item.SubItems[0].Text = friend; if (info == "n") { new_item.SubItems.Add("offline"); } else { new_item.SubItems.Add("online"); } listView1.Items.Add(new_item); } else { if (info == "n") { listView1.Items[i].SubItems[1].Text = "offline"; } else { listView1.Items[i].SubItems[1].Text = "online"; } } } } //Console.WriteLine(DateTime.Now.ToString() + "\n"); } //Thread.Sleep(500); //get_friend_list(); }
//添加朋友 private void button_addfriend_Click(object sender, EventArgs e) { string friend_name = textBox_friendname.Text; bool state = true; //判断是否已经是好友 foreach (ListViewItem item in listView1.Items) { if (friend_name == item.Text) { MessageBox.Show(this, "已经在好友列表中", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); state = false; break; } } //判断是否存在该账号 if (state) { string recv_str = Server_Connection.Search_Friend(friend_name, client_socket); if (recv_str == "Incorrect No." || recv_str == "Please send the right message") { MessageBox.Show(this, "用户不存在", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { string search_text = "Select username from user_table where username="******"该用户还未注册", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else if (recv_str == "n") { MessageBox.Show(this, "该用户不在线,请稍后再试", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { Socket add_friend_socket = P2P_Communication.Commun_Friend(friend_name, client_socket); string send_msg = "a." + user_name; P2P_Communication.Connect_Send(add_friend_socket, send_msg); Thread.Sleep(10); add_friend_socket.Shutdown(SocketShutdown.Both); add_friend_socket.Close(); } } } }
//主动与朋友发起聊天 创建套接字 public static Socket Commun_Friend(string friend_name, Socket socket_to_server) { Socket socket_to_friend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); string friend_ip = Server_Connection.Search_Friend(friend_name, socket_to_server); if (friend_ip != "Incorrect login No." && friend_ip != "Please send the correct message.") { IPEndPoint endPoint; int target_port; target_port = Convert.ToInt32(friend_name.Substring(6)) + 50000; endPoint = new IPEndPoint(IPAddress.Parse(friend_ip), target_port); //socket_to_friend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //socket_to_friends[i] = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket_to_friend.Connect(endPoint); } return(socket_to_friend); }