private void button_login_Click(object sender, EventArgs e) { Net_class NC = new Net_class(textBox_serverIP.Text, int.Parse(textBox_serverPort.Text)); //自定义类,处理网络事件 NC.try_connect(6000); if (!NC.sock.Connected) { DialogResult dr = MessageBox.Show(this, "无法连接到服务器,请检查服务器信息。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); NC.Close(); return; } string user_name = textBox_userName.Text; NC.Send_message(user_name + "_" + textBox_password.Text);//发送用户名密码 string receive_string = NC.Receive_string(); if (receive_string == "lol") { DialogResult dr = MessageBox.Show(this, "登录成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { DialogResult dr = MessageBox.Show(this, "登录失败,请检查用户名密码。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Thread Thread_friendList = new Thread(() => Application.Run(new FriendList(user_name, NC))); Thread_friendList.Start(); this.Close(); }
//聊天监听的callback public void clientChat_accepted(IAsyncResult asy_result) { Socket listen_socket = (Socket)asy_result.AsyncState; Socket receive_socket = listen_socket.EndAccept(asy_result); Net_class receive_net = new Net_class(receive_socket); int my_receive_port = receive_net.get_my_port(); if (my_receive_port == Net_class.client_listenChat_port) //在聊天的监听端口接收到请求,则给对方返回一个本地可用的端口后并监听该端口号 { chat_receive_port += 1; while (Net_class.portInUse(chat_receive_port)) //判断端口chat_receive_port是否被占用,如果是则加1 { chat_receive_port += 1; } receive_net.Send_message_asy(chat_receive_port.ToString()); //向对方发送可用端口号 string myIP = Net_class.getMy_ip(); Net_class listenChat_custom_NC = new Net_class(); listenChat_custom_NC.bind_ip_port(myIP, chat_receive_port); listenChat_custom_NC.sock.Listen(200); listenChat_custom_NC.sock.BeginAccept(new AsyncCallback(clientChat_accepted), listenChat_custom_NC.sock); } else if (chatting_ports.FindIndex(x => x == my_receive_port) == -1) //不是正在聊天的窗口所发来的连接 { //开启接收消息 receive_socket.BeginReceive(buffer_Chat, 0, buffer_Chat.Length, SocketFlags.None, new AsyncCallback(clientChat_receive), receive_socket); } //开始接受下一个聊天请求 listen_socket.BeginAccept(new AsyncCallback(clientChat_accepted), listen_socket); }
//开启监听 public void Listen_message() { try { //添加好友的监听 Net_class listenF_NC = new Net_class(); string myIP = Net_class.getMy_ip(); listenF_NC.bind_ip_port(myIP, Net_class.client_listenF_port); listenF_NC.sock.Listen(200); listenF_NC.sock.BeginAccept(new AsyncCallback(clientF_accepted), listenF_NC.sock); //聊天的监听 Net_class listenChat_NC = new Net_class(); listenChat_NC.bind_ip_port(myIP, Net_class.client_listenChat_port); listenChat_NC.sock.Listen(200); listenChat_NC.sock.BeginAccept(new AsyncCallback(clientChat_accepted), listenChat_NC.sock); //群聊的监听 Net_class listenGroupChat_NC = new Net_class(); listenGroupChat_NC.bind_ip_port(myIP, Net_class.client_listenGroupChat_port); listenGroupChat_NC.sock.Listen(200); listenGroupChat_NC.sock.BeginAccept(new AsyncCallback(clientGroupChat_accepted), listenGroupChat_NC.sock); } catch (SocketException e) { MessageBox.Show("端口被占用。" + e.ToString(), "异常", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//群聊监听的callback public void clientGroupChat_accepted(IAsyncResult asy_result) { Socket listen_socket = (Socket)asy_result.AsyncState; Socket receive_socket = listen_socket.EndAccept(asy_result); Net_class receive_net = new Net_class(receive_socket); int my_receive_port = receive_net.get_my_port(); if (my_receive_port == Net_class.client_listenGroupChat_port) //在群聊的监听端口接收到请求,则给对方返回一个本地可用的端口后并监听该端口号 { groupChat_receive_port += 1; while (Net_class.portInUse(groupChat_receive_port)) //判断端口chat_receive_port是否被占用,如果是则加1 { groupChat_receive_port += 1; } receive_net.Send_message_asy(groupChat_receive_port.ToString()); //向对方发送可用端口号 string myIP = Net_class.getMy_ip(); Net_class listenGroupChat_custom_NC = new Net_class(); listenGroupChat_custom_NC.bind_ip_port(myIP, groupChat_receive_port); listenGroupChat_custom_NC.sock.Listen(200); listenGroupChat_custom_NC.sock.BeginAccept(new AsyncCallback(clientGroupChat_accepted), listenGroupChat_custom_NC.sock); } else if (group_chatting_ports.FindIndex(x => x == my_receive_port) == -1) //不是正在聊天的窗口所发来的连接 { groupChatWindow CW = new groupChatWindow(receive_net, myName); Thread Thread_friendList = new Thread(() => Application.Run(CW)); Thread_friendList.SetApartmentState(ApartmentState.STA); //要加这句,否则不能打开fileopendialog Thread_friendList.Start(); group_chatting_ports.Add(my_receive_port); } listen_socket.BeginAccept(new AsyncCallback(clientGroupChat_accepted), listen_socket); }
private void button_groupTalk_Click(object sender, EventArgs e) { int member_num = listView_friendList.SelectedItems.Count; if (member_num == 0) { MessageBox.Show(this, "请先选择群聊成员!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Dictionary <string, Net_class> connected_name_NC = new Dictionary <string, Net_class>(); List <string> failed_names = new List <string>(); for (int i = 0; i < member_num; i++) { string his_name = listView_friendList.SelectedItems[i].Text; string his_ip = Friends_ip[his_name]; Net_class NC_chat_apply = new Net_class(his_ip, Net_class.client_listenGroupChat_port); NC_chat_apply.try_connect(3000); if (!NC_chat_apply.sock.Connected) { failed_names.Add(his_name); continue; } string new_port_str = NC_chat_apply.Receive_string(); //接收对方传来的端口信息。 Net_class NC_chat_new = new Net_class(his_ip, int.Parse(new_port_str)); NC_chat_new.try_connect(3000); if (!NC_chat_new.sock.Connected) { failed_names.Add(his_name); continue; } connected_name_NC.Add(his_name, NC_chat_new); } groupChatWindow CW = new groupChatWindow(connected_name_NC, myName); Thread Thread_friendList = new Thread(() => Application.Run(CW)); Thread_friendList.SetApartmentState(ApartmentState.STA); //要加这句,否则不能打开fileopendialog Thread_friendList.Start(); if (failed_names.Count > 0) { string failed_names_str = ""; for (int i = 0; i < failed_names.Count; i++) { failed_names_str = failed_names_str.Insert(failed_names_str.Length, failed_names[i] + " "); } MessageBox.Show(this, "下列用户连接失败:\r\n " + failed_names_str, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//成员初始化 public groupChatWindow(Net_class connected, string my_name_in) { common_init(); my_name = my_name_in; host_connectNC = connected; host_flag = false; host_connectNC.sock.BeginReceive(buffer_member_receive, 0, buffer_member_receive.Length, SocketFlags.None, new AsyncCallback(member_receive), host_connectNC.sock); //异步接收 }
void addChatWin(string his_ip, string his_name, Net_class NC) { //chatWindow CW = new chatWindow(his_ip, Net_class.getMy_ip(), his_name, myName, NC_chat_apply); //CW.Show(); chatWindow CW = new chatWindow(his_ip, Net_class.getMy_ip(), his_name, myName, NC); //ChatWinDic.Add(his_name, CW); Thread Thread_friendList = new Thread(() => Application.Run(CW)); Thread_friendList.SetApartmentState(ApartmentState.STA); //要加这句,否则不能打开fileopendialog Thread_friendList.Start(); }
private void button_addFriend_Click(object sender, EventArgs e) { addFriend aF = new addFriend(); aF.ShowDialog(); string friend_name = aF.friend_name; if (friend_name == "") { return; } server_NC.Send_message("q" + friend_name);//查询好友状态 string receive_string = server_NC.Receive_string(); if (receive_string == "n" || receive_string.StartsWith("Please")) { DialogResult dr = MessageBox.Show(this, "对方不在线,添加好友失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } else { Net_class NC_friend_apply = new Net_class(receive_string, Net_class.client_listenF_port); NC_friend_apply.try_connect(3000); if (!NC_friend_apply.sock.Connected) { DialogResult dr = MessageBox.Show(this, "无法连接到对方网络,请稍后重试。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } /*try * { NC_friend_apply.try_connect(); } * catch(SocketException) * { * DialogResult dr = MessageBox.Show(this, "无法连接到对方网络,请稍后重试。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); * return; * }*/ NC_friend_apply.Send_message("_f" + myName); //发送好友申请 Thread thr = new Thread(() => MessageBox.Show("已发送好友申请!\r\n对方在线。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)); //显示提示窗口但不将程序挂起 thr.IsBackground = true; thr.Start(); //NC_friend_apply.Close(); } }
public FriendList(string in_myName, Net_class NC) { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; listView_friendList.Columns[0].Width = 100; listView_friendList.Columns[1].Width = 120; listView_friendList.Columns[2].Width = 100; myName = in_myName; server_NC = NC; listView_friendList.DoubleClick += new EventHandler(listView_friendList_DoubleClick); //注册鼠标双击事件 FormClosing += new FormClosingEventHandler(friendList_FormClosing); //注册窗口关闭事件 Listen_message(); }
public chatWindow(string in_his_ip, string in_my_ip, string in_his_name, string in_my_name, Net_class sock) { InitializeComponent(); FormClosing += new FormClosingEventHandler(chatWindow_FormClosing); //注册窗口关闭事件 listView_message.Columns[0].Width = 100; listView_message.Columns[0].TextAlign = HorizontalAlignment.Center; listView_message.Columns[1].Width = listView_message.Width - listView_message.Columns[0].Width; his_ip = in_his_ip; my_ip = in_my_ip; his_name = in_his_name; my_name = in_my_name; Sock_connected = sock; this.Text = "聊天:" + his_name; sock.sock.BeginReceive(buffer_Chat_receive, 0, buffer_Chat_receive.Length, SocketFlags.None, new AsyncCallback(clientChat_receive), sock.sock); //异步接收 }
//发起聊天 private void listView_friendList_DoubleClick(object sender, EventArgs e) { if (listView_friendList.SelectedItems.Count == 0) { return; } string his_name = listView_friendList.SelectedItems[0].Text; string his_ip = Friends_ip[his_name]; Net_class NC_chat_apply = new Net_class(his_ip, Net_class.client_listenChat_port); /*Thread thr = new Thread(() => MessageBox.Show("连接中。。。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)); //显示提示窗口但不将程序挂起 * thr.IsBackground = true; * thr.Start();*/ NC_chat_apply.try_connect(3000); if (!NC_chat_apply.sock.Connected) { DialogResult dr = MessageBox.Show(this, "连接对方网络失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string new_port_str = NC_chat_apply.Receive_string(); //接收对方传来的端口信息。 Net_class NC_chat_new = new Net_class(his_ip, int.Parse(new_port_str)); NC_chat_new.try_connect(3000); if (!NC_chat_new.sock.Connected) { DialogResult dr = MessageBox.Show(this, "连接对方网络失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } NC_chat_new.Send_message("_c" + myName); addChatWin(his_ip, his_name, NC_chat_new); }
//收到聊天消息的callback public void clientChat_receive(IAsyncResult asy_result) { Socket receive_socket = (Socket)asy_result.AsyncState; Net_class receive_NC = new Net_class(receive_socket); int my_receive_port = receive_NC.get_my_port(); IPEndPoint friend_endP = (IPEndPoint)receive_socket.RemoteEndPoint; string friend_ip = friend_endP.Address.ToString(); try { int len; string message = receive_NC.Receive_string(asy_result, buffer_Chat, out len); //聊天邀请 if (message.Length > 2 && message.StartsWith("_c")) { string his_name = message.Substring(2); string his_ip = friend_ip; //Friends_ip.TryGetValue(his_name, out his_ip); if (!receive_NC.sock.Connected) { DialogResult dr = MessageBox.Show(this, "与用户:" + his_name + "的聊天创建失败。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } chatting_ports.Add(my_receive_port); addChatWin(his_ip, his_name, receive_NC); } } catch (SocketException e) { MessageBox.Show(e.ToString(), "异常", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//收到消息 public void clientChat_receive(IAsyncResult asy_result) { Net_class receive_NC; Socket receive_socket; if (!Sock_connected.sock.Connected) { Sock_connected.Close(); Close(); return; } try { receive_socket = (Socket)asy_result.AsyncState; receive_NC = new Net_class(receive_socket); IPEndPoint friend_endP = (IPEndPoint)receive_socket.RemoteEndPoint; string friend_ip = friend_endP.Address.ToString(); } catch { return; } try { int receive_len; string message = receive_NC.Receive_string(asy_result, buffer_Chat_receive, out receive_len); //聊天信息 if (message.Length > 1 && message[0] == 1) { message = message.Substring(1); string his_name = (message.Split('_')[0]); add_msg2list(his_name, message.Split('_')[1], Color.Black); } //收到文件 else if (receive_len > 1 && buffer_Chat_receive[0] == 2) { string file_suffix = file_name.Substring(file_name.LastIndexOf('.')); DialogResult re = MessageBox.Show("对方发来文件:" + file_name + ",是否接收?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (re == DialogResult.No) { return; } SaveFileDialog save_file_Dialog = new SaveFileDialog() { Filter = "(*" + file_suffix + ")|*" + file_suffix + "", FileName = file_name }; string savePath; if (save_file_Dialog.ShowDialog(this) == DialogResult.OK) { savePath = save_file_Dialog.FileName; using (FileStream fs = new FileStream(savePath, FileMode.Append, FileAccess.Write)) { fs.Write(buffer_Chat_receive, 1, receive_len - 1); fs.Flush(); fs.Close(); } add_msg2list("系统消息:", "接受到的文件已经保存:" + savePath, Color.Red); } } //收到文件名 else if (receive_len > 1 && buffer_Chat_receive[0] == 3) { message = message.Substring(1); file_name = message; } receive_socket.BeginReceive(buffer_Chat_receive, 0, buffer_Chat_receive.Length, SocketFlags.None, new AsyncCallback(clientChat_receive), receive_socket); } catch (SocketException e) { //MessageBox.Show(e.ToString(), "异常", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//房主等待每位群成员的消息 public void host_receive(string his_name, Net_class connected_NC) { myFileInfo last_fileInfo = new myFileInfo(0, ""); while (true) { if (!connected_NC.sock.Connected) { return; } int info_length; byte[] receive_info = connected_NC.Receive_bytes(out info_length); string msg = Encoding.UTF8.GetString(receive_info, 1, info_length - 1); //文字消息 if (info_length > 0 && receive_info[0] == 0) { add_msg2list(his_name, msg, Color.Black); send_msg2all(his_name, msg, false); } //文件 else if (info_length > 0 && receive_info[0] == 2) { if (last_fileInfo.length == 0) { continue; } byte[] file_bytes = new byte[info_length - 1]; Buffer.BlockCopy(receive_info, 1, file_bytes, 0, info_length - 1); host_file_list.Add(last_fileInfo, file_bytes); add_file2list(last_fileInfo, his_name, Color.Black); send_fileInfo2all_users(last_fileInfo, his_name); } //文件长度和文件名 else if (info_length > 1 && receive_info[0] == 3) { string[] msg_split = msg.Split('_'); long file_len; if (!long.TryParse(msg_split[0], out file_len)) { continue; } string file_name = msg_split[1]; for (int i = 2; i < msg_split.Length; i++) { file_name += ("_" + msg_split[i]); } last_fileInfo = new myFileInfo(file_len, file_name); } //用户退出消息 else if (info_length > 1 && receive_info[0] == 4) { if (msg == "q") { for (int i = 1; i < listView_members.Items.Count; i++) { string item_name = listView_members.Items[i].SubItems[1].Text; if (item_name == his_name) { listView_members.Items.Remove(listView_members.Items[i]); } } connected_name_NC[his_name].Close(); connected_name_NC.Remove(his_name); return; } } //请求文件 else if (info_length > 1 && receive_info[0] == 5) { string[] msg_split = msg.Split('_'); myFileInfo get_fileInfo = new myFileInfo(); if (!long.TryParse(msg_split[0], out get_fileInfo.length)) { continue; } get_fileInfo.name = msg_split[1]; for (int i = 2; i < msg_split.Length; i++) { get_fileInfo.name += ("_" + msg_split[i]); } byte[] file_byte; if (!host_file_list.TryGetValue(get_fileInfo, out file_byte)) { connected_name_NC[his_name].Send_message_NumString_asy(5, "n"); } else { connected_name_NC[his_name].Send_message_NumByte_asy(2, file_byte, file_byte.Length); } } } }
public chatWindow(string in_his_ip, string in_my_ip, string in_his_name, string in_my_name, Net_class sock) { InitializeComponent(); FormClosing += new FormClosingEventHandler(chatWindow_FormClosing); //注册窗口关闭事件 listView_message.Columns[0].Width = 100; listView_message.Columns[0].TextAlign = HorizontalAlignment.Center; listView_message.Columns[1].Width = listView_message.Width - listView_message.Columns[0].Width; his_port = sock.get_his_port(); my_port = sock.get_my_port(); his_ip = in_his_ip; my_ip = in_my_ip; his_name = in_his_name; my_name = in_my_name; this.Text = "聊天:" + his_name; sock.Close(); receive_sock = new UdpClient(my_port); send_sock = new UdpClient(); CheckForIllegalCrossThreadCalls = false; receive_tr = new Thread(new ThreadStart(clientChat_receive)); receive_tr.IsBackground = true; receive_tr.Start(); }
//成员接收到信息的callback public void member_receive(IAsyncResult asy_result) { Net_class receive_NC; Socket receive_socket; if (!host_connectNC.sock.Connected) { host_connectNC.Close(); Close(); return; } try { receive_socket = (Socket)asy_result.AsyncState; receive_NC = new Net_class(receive_socket); IPEndPoint friend_endP = (IPEndPoint)receive_socket.RemoteEndPoint; string friend_ip = friend_endP.Address.ToString(); } catch { return; } try { int receive_len; string message = receive_NC.Receive_string(asy_result, buffer_member_receive, out receive_len); //聊天信息 if (receive_len > 1 && message[0] == 0) { parse_string_msg(buffer_member_receive, receive_len, out string his_name, out string msg); add_msg2list(his_name, msg, Color.Black); } //收到成员名 else if (receive_len > 1 && buffer_member_receive[0] == 1) { listView_members.Items.Clear();//首先清空列表 int name_num = (receive_len - 1) / name_len; string host_name = message.Substring(1, name_len); addMember2list("群主", host_name, Color.Black); for (int i = 1; i < name_num; i++) { string his_name = message.Substring(1 + name_len * i, name_len); Color c = his_name == my_name ? Color.Green : Color.Black; addMember2list("成员", his_name, c); } } //收到文件 else if (receive_len > 1 && buffer_member_receive[0] == 2) { string file_suffix = applying_file.name.Substring(applying_file.name.LastIndexOf('.')); DialogResult re = MessageBox.Show("文件已收到:" + applying_file.name + ",是否接收?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (re == DialogResult.No) { return; } SaveFileDialog save_file_Dialog = new SaveFileDialog() { Filter = "(*" + file_suffix + ")|*" + file_suffix + "", FileName = applying_file.name }; string savePath; if (save_file_Dialog.ShowDialog(this) == DialogResult.OK) { savePath = save_file_Dialog.FileName; using (FileStream fs = new FileStream(savePath, FileMode.Append, FileAccess.Write)) { fs.Write(buffer_member_receive, 1, receive_len - 1); fs.Flush(); fs.Close(); } add_msg2list("系统消息:", "接受到的文件已经保存:" + savePath, Color.Red); } } //收到文件信息 else if (receive_len > 1 && buffer_member_receive[0] == 3) { if (parse_file_msg(buffer_member_receive, receive_len, out string his_name, out myFileInfo file_info)) { add_file2list(file_info, his_name, Color.Black); } } //群组解散 else if (receive_len > 1 && buffer_member_receive[0] == 4) { string msg = Encoding.UTF8.GetString(buffer_member_receive, 1, receive_len - 1); if (msg == "q") { MessageBox.Show("群组已解散!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); client_activeClose = false; host_connectNC.Close(); this.Close(); return; } } //没有找到文件 if (receive_len > 1 && message[0] == 5) { add_msg2list("系统消息:", "没有找到文件:" + applying_file.name, Color.Red); } receive_socket.BeginReceive(buffer_member_receive, 0, buffer_member_receive.Length, SocketFlags.None, new AsyncCallback(member_receive), receive_socket); } catch (SocketException e) { //MessageBox.Show(e.ToString(), "异常", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
//收到添加好友消息的callback public void clientF_receive(IAsyncResult asy_result) { Socket receive_socket = (Socket)asy_result.AsyncState; Net_class receive_NC = new Net_class(receive_socket); IPEndPoint friend_endP = (IPEndPoint)receive_socket.RemoteEndPoint; string friend_ip = friend_endP.Address.ToString(); try { int len; string message = receive_NC.Receive_string(asy_result, buffer_F, out len); if (message.Length < 3) { return; } string friend_name = message.Substring(2); if (message.StartsWith("_f")) //收到好友申请 { DialogResult dr = MessageBox.Show(this, "用户:" + friend_name + " 请求添加好友,是否同意?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information); string friend_reply; if (dr == DialogResult.Yes) //接收好友申请 { friend_reply = "_y"; add_friend2list(friend_name, friend_ip); } else //拒绝好友申请 { friend_reply = "_n"; } Net_class NC_friend_agree = new Net_class(friend_ip, Net_class.client_listenF_port); NC_friend_agree.try_connect(3000); if (!NC_friend_agree.sock.Connected) { MessageBox.Show(this, "无法连接到对方网络,请稍后重试。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } NC_friend_agree.Send_message(friend_reply + myName); //发送回复 if (dr == DialogResult.Yes) //添加到好友列表 { add_friend2list(friend_name, friend_ip); } } else if (message.StartsWith("_y")) //好友申请被接受 { DialogResult dr = MessageBox.Show(this, "用户:" + friend_name + " 已接受您的好友申请。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); add_friend2list(friend_name, friend_ip); } else if (message.StartsWith("_n")) { DialogResult dr = MessageBox.Show(this, "用户:" + friend_name + " 已拒绝您的好友申请。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } //receive_NC.sock.BeginReceive(buffer_F, 0, buffer_F.Length, SocketFlags.None, new AsyncCallback(clientF_receive), receive_NC.sock); } catch (SocketException e) { MessageBox.Show(e.ToString(), "异常", MessageBoxButtons.OK, MessageBoxIcon.Error); } }