日期:2014-05-18  浏览次数:20894 次

请教一个关于SOCKET异步接受信息的问题
前提 有一个类监听类,用来监听或者说是用来接收数据的。
C# code

public void StartListening(string ip)
        {
            serverSK = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip), 9095);
            try
            {
                allDone.Reset();
                serverSK.BeginAccept(new AsyncCallback(AcceptCallback), serverSK);
                allDone.WaitOne();
            }
            catch
            { }
        }
 public void AcceptCallback(IAsyncResult ar)
        {
            try
            {
                allDone.Set();
                Socket listener = ar.AsyncState as Socket;
                Socket handler = listener.EndAccept(ar);
                listener.BeginAccept(new AsyncCallback(AcceptCallback), handler);
                byte[] buffer = new byte[1024];
                SocketHelper helper = new SocketHelper(buffer, handler);

                handler.BeginReceive(buffer, 0, 1, SocketFlags.None, new AsyncCallback(Receive), helper);
            }
            catch
            {
                //
            }
        }
 void Receive(IAsyncResult ia)
        {
            SocketHelper helper = ia.AsyncState as SocketHelper;

            Socket worker = helper.s;
            worker.EndReceive(ia);

            byte[] buffer = new byte[worker.Available + 1];
            worker.Receive(buffer, 1, buffer.Length - 1, SocketFlags.None);
            buffer[0] = helper.b[0];

            this.sendBackSocket = worker;
            //调用事件
            this.OnMessageArrival(new AsyncEventArgs(buffer));

            worker.BeginReceive(helper.b, 0, 1, SocketFlags.None, new AsyncCallback(Receive), helper);
        }

 /// <summary>
        /// 触发消息抵达事件
        /// </summary>
        /// <param name="e">收到的字节数组</param>
        private void OnMessageArrival(AsyncEventArgs e)
        {
            if (this.receiveEventHandler != null)
            {
                this.receiveEventHandler(this, e);
            }
        }



我在Form实例化了它,当我 接受到数据的时候 如何显示在Form中的text中啊?

因为是异步的嘛。而且值在Receive函数中才可以取到。

求请教啊

如何能在值收到的时候返回给Form中的Text啊?

------解决方案--------------------
沙发+Mark+帮顶+如下:
C# code

 /// <summary>
        /// 触发消息抵达事件
        /// </summary>
        /// <param name="e">收到的字节数组</param>
        private void OnMessageArrival(AsyncEventArgs e)
        {
            if (this.receiveEventHandler != null)
            {
                this.text.BeginInvoke(new AsyncCallback(setText),Encoding.UTF8.GetString((byte[])e));
                this.receiveEventHandler(this, e);
            }
        }


public void setText(IAsyncResult ia)
{

}