//聊天监听的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); }
//群聊监听的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); }