private void ReceiveCallback(IAsyncResult ar) { MyFriend frd = (MyFriend)ar.AsyncState; try { int i = frd.socket.EndReceive(ar); if (i == 0) { comboBoxClient.Invoke(Removefriend, frd); return; } else { string data = Encoding.UTF8.GetString(frd.Rcvbuffer, 0, i); infoData = data; //将传来的数据传给infoData lineNum = listBoxStatu.Items.Count; //将行数赋值给lineNum data = string.Format("From[{0}]:{1}", frd.socket.RemoteEndPoint.ToString(), data); comboBoxClient.SelectedItem = (frd.socket.RemoteEndPoint.ToString()); //收到信息之后选中发送信息的ip listBoxStatu.Invoke(AppendString, data); frd.ClearBuffer(); AsyncCallback callback = new AsyncCallback(ReceiveCallback); frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, callback, frd); } } catch { comboBoxClient.Invoke(Removefriend, frd); } }
private void AcceptCallBack(IAsyncResult ar) { try { //完成异步接收连接请求的异步调用 //将连接信息添加到列表和下拉列表中 Socket handle = listener.EndAcceptSocket(ar); MyFriend frd = new MyFriend(handle); comboBoxClient.Invoke(Addfriend, frd); AsyncCallback callback; //继续调用异步方法接收连接请求 if (IsStart) { callback = new AsyncCallback(AcceptCallBack); listener.BeginAcceptSocket(callback, listener); } //开始在连接上进行异步的数据接收 frd.ClearBuffer(); callback = new AsyncCallback(ReceiveCallback); frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, callback, frd); } catch { //在调用EndAcceptSocket方法时可能引发异常 //套接字Listener被关闭,则设置为未启动侦听状态 IsStart = false; } }