private void ReceiveCallback(IAsyncResult ar) { MyFriend frd = (MyFriend)ar.AsyncState; try { int i = frd.socket.EndReceive(ar); if (i == 0) { return; } else { string data = Encoding.UTF8.GetString(frd.Rcvbuffer, 0, i); data = string.Format("{0}", data); listBoxStatu.Invoke(AppendString, data); frd.ClearBuffer(); AsyncCallback callback = new AsyncCallback(ReceiveCallback); frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, callback, frd); TextWriter tw = new StreamWriter("C:/Users/jerry/Desktop/data.csv", false); tw.WriteLine(data); tw.Close(); } } catch { } }
private void AddMethod(MyFriend frd) { lock (friends) { friends.Add(frd); } }
//向下拉列表中添加信息的委托方法 private void AddMethod(MyFriend frd) { lock (friends) { friends.Add(frd); } comboBoxClient.Items.Add(frd.socket.RemoteEndPoint.ToString()); }
private void RemoveMethod(MyFriend frd) { int i = friends.IndexOf(frd); lock (friends) { friends.Remove(frd); } frd.Dispose(); }
//从下拉列表中删除信息的委托方法 private void RemoveMethod(MyFriend frd) { int i = friends.IndexOf(frd); comboBoxClient.Items.RemoveAt(i); lock (friends) { friends.Remove(frd); } frd.Dispose(); }
private void AcceptCallBack(IAsyncResult ar) { try { Socket handle = listener.EndAcceptSocket(ar); MyFriend frd = new MyFriend(handle); AsyncCallback callback; if (IsStart) { callback = new AsyncCallback(AcceptCallBack); listener.BeginAcceptSocket(callback, listener); } //async frd.ClearBuffer(); callback = new AsyncCallback(ReceiveCallback); frd.socket.BeginReceive(frd.Rcvbuffer, 0, frd.Rcvbuffer.Length, SocketFlags.None, callback, frd); } catch { IsStart = false; } }
//发送信息 private void SendData(MyFriend frd, string data) { try { //获取需要发送的信息 byte[] msg = Encoding.UTF8.GetBytes(data); //异步调用发送信息 AsyncCallback callback = new AsyncCallback(SendCallback); frd.socket.BeginSend(msg, 0, msg.Length, SocketFlags.None, callback, frd); //更新UI data = string.Format("To[{0}]:{1}", frd.socket.RemoteEndPoint.ToString(), data); listBoxStatu.Invoke(AppendString, data); } 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);//更新UI //继续调用异步方法接收连接请求 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; } }