Exemplo n.º 1
0
        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
            {
            }
        }
Exemplo n.º 2
0
 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;
     }
 }
Exemplo n.º 3
0
        //等待回调
        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;
            }
        }