Socket OnData事件

时间:2012-10-13 04:50:28

标签: c# sockets events

我目前处于一个小小的泡菜中。我有一些代码可以在数据可用时从套接字读取数据,但是当前它在一个单独的线程中处于while循环中,并且当函数返回时由于没有数据可用而咀嚼50%的CPU。我真正想要的是套接字的阻塞功能,它阻塞直到数据可用,或者至少是一个可以监听的OnData事件。我最初从AS3(Flash)转换了这个代码,但是他们的套接字类有我需要的OnData事件......只是用错误的语言。

我目前在处理客户端连接的代码中有这段代码:

ServerThread = new Thread(() =>
{
    while (server.Connected && ServerContinue)
    {
        ReceiveFromServer(server, client);
    }

    Disconnect(server, client, false);
});

ServerThread.Start();

这是ReceiveFromServer中的代码:

bool isReady = false;
int messageLength = 0;
int dataAvailable = 0;
UInt16 packetSize = 0;
byte[] temp = new byte[2];
do
{
    dataAvailable = server.Available;
    if (isReady)
    {
        if (dataAvailable >= messageLength)
        {
            byte[] temp1 = new byte[2000];
            int bytesRead = server.Receive(temp1, 0, messageLength, SocketFlags.None);

            byte[] data = new byte[bytesRead + 2];
            Buffer.BlockCopy(temp1, 0, data, 2, messageLength);

            Helpers.ByteArray tempo = data;
            tempo.writeByte(temp[1]);
            tempo.writeByte(temp[0]);
            if (!VersionCheckPass)
            {
                Send(tempo, client);
                return;
            }

            ServerPacketHandler(tempo, client);
            messageLength = 0;
            isReady = false;
            temp = new byte[2];
        }
    }
    else if(dataAvailable > 2)
    {
        server.Receive(temp, 0, 2, SocketFlags.None);
        temp = temp.Reverse().ToArray();
        packetSize = BitConverter.ToUInt16(temp, 0);
        if (packetSize > 0)
        {
            messageLength = packetSize;
            isReady = true;
        }
    }
}
while (dataAvailable > 2 && dataAvailable >= messageLength && ServerContinue);

但问题是当dataAvailable为0时,函数只返回,然后在线程中再次调用RecevieFromServer。这意味着通过简单地调用ReceiveFromServer然后再次返回来使用很多CPU。

我目前在ServerThread中的ReceiveFromServer之后有Thread.Sleep(10),但效率很低。所以我的问题是,有没有办法阻止数据可用或是否有我可以处理的事件?或者其他人对如何做我目前正在做的事情有任何建议,但它没有无限循环,而没有可用数据。

2 个答案:

答案 0 :(得分:1)

找到一个非常简单(明显)的解决方案,直到数据可用为止。调用Socket.Receive,接收大小为0.套接字阻塞,直到有数据要接收,然后从套接字读取0个字节,然后解除阻塞。它真的很奇妙:)继承人我是如何实现它的:

ServerThread = new Thread(() =>
{
    byte[] zero = new byte[0];
    while (Server.Connected && ServerContinue)
    {
        server.Receive(zero, 0, SocketFlags.None);
        ReceiveFromServer(server, client);
    }

    Disconnect(server, client, false);
});

感谢您的帮助。

约什

答案 1 :(得分:0)

不需要进行大量重写。您的代码看起来只是接收消息,然后传递给另一个例程来处理它。

我对这个帖子的回复几乎涵盖了你想要做的事情:

C# Sockets and Multithreading

我的socketReadCallBack函数是:

    private void OnDataReceived(IAsyncResult asyn)
    {
        ReceiveState rState = (ReceiveState)asyn.AsyncState;
        Socket client = rState.Client;
        SocketError socketError = SocketError.TypeNotFound;

        if (!client.Connected)
        {
            // Not Connected anymore ?
            return;
        }

        _LastComms = DateTime.Now;
        _LastIn = _LastComms;

        int dataOffset = 0; 
        int restOfData = 0;
        int dataRead = 0;
        Boolean StreamClosed = false;
        long rStateDataLength = 0;
        long LastrStateDataLength = 0;

        try
        {

            dataRead = client.EndReceive(asyn, out socketError);
        }
        catch (Exception excpt)
        {
            // Handle error - use your own code..

        }

        if (socketError != SocketError.Success)
        {
            // Has Connection been lost ?
            OnConnectionDropped(client);
            return;
        }

        if (dataRead <= 0)
        {
            // Has connection been lost ?
            OnConnectionDropped(client);
            return;
        }

        while (dataRead > 0)
        {
            //check to determine what income data contain: size prefix or message
            if (!rState.DataSizeReceived)
            {
                //there is already some data in the buffer
                if (rState.Data.Length > 0)
                {
                    restOfData = PrefixSize - (int)rState.Data.Length;
                    rState.Data.Write(rState.Buffer, dataOffset, restOfData);
                    dataRead -= restOfData;
                    dataOffset += restOfData;
                }
                else if (dataRead >= PrefixSize)
                {  //store whole data size prefix
                    rState.Data.Write(rState.Buffer, dataOffset, PrefixSize);
                    dataRead -= PrefixSize;
                    dataOffset += PrefixSize;
                }
                else
                {  // store only part of the size prefix
                    rState.Data.Write(rState.Buffer, dataOffset, dataRead);
                    dataOffset += dataRead;
                    dataRead = 0;
                }

                if (rState.Data.Length == PrefixSize)
                {  //we received data size prefix 
                    rState.DataSize = BitConverter.ToInt32(rState.Data.GetBuffer(), 0);
                    rState.DataSizeReceived = true;
                    //reset internal data stream             
                    rState.Data.Position = 0;
                    rState.Data.SetLength(0);
                }
                else
                {  //we received just part of the prefix information 
                    //issue another read
                    client.BeginReceive(rState.Buffer, 0, rState.Buffer.Length,
                       SocketFlags.None, new AsyncCallback(socketReadCallBack),
                          rState);
                    return;
                }
            }



            //at this point we know the size of the pending data

            // Object disposed exception may raise here
            try
            {
                rStateDataLength = rState.Data.Length;
                LastrStateDataLength = rStateDataLength;
            }
            catch (ObjectDisposedException Ode)
            {
                StreamClosed = true;
            }
            if (!StreamClosed)
            {

                if ((rStateDataLength + dataRead) >= rState.DataSize)
                {   //we have all the data for this message

                    restOfData = rState.DataSize - (int)rState.Data.Length;

                    rState.Data.Write(rState.Buffer, dataOffset, restOfData);
                    //Console.WriteLine("Data message received. Size: {0}",
                    //   rState.DataSize);

                    // Is this a heartbeat message ?
                    if (rState.Data.Length == 2)
                    {
                        // Yes
                        HeartBeatReceived();
                    }
                    else
                    {
                        //charArray = new char[uniEncoding.GetCharCount(
                        //byteArray, 0, count)];
                        //uniEncoding.GetDecoder().GetChars(
                        //    byteArray, 0, count, charArray, 0);
                        //Console.WriteLine(charArray);

                        //rState.Data.Position = 0;

                        DecodeMessageReceived(GetStringFromStream(rState.Data));
                    }

                    dataOffset += restOfData;
                    dataRead -= restOfData;

                    //message received - cleanup internal memory stream
                    rState.Data = new MemoryStream();
                    rState.Data.Position = 0;
                    rState.DataSizeReceived = false;
                    rState.DataSize = 0;

                    if (dataRead == 0)
                    {  
                        //no more data remaining to process - issue another receive
                        if (_IsConnected)
                        {
                            client.BeginReceive(rState.Buffer, 0, rState.Buffer.Length,
                               SocketFlags.None, new AsyncCallback(socketReadCallBack),
                                  rState);
                            return;
                        }
                    }
                    else
                        continue; //there's still some data to process in the buffers
                }
                else
                {  //there is still data pending, store what we've 
                    //received and issue another BeginReceive
                    if (_IsConnected)
                    {
                        rState.Data.Write(rState.Buffer, dataOffset, dataRead);

                        client.BeginReceive(rState.Buffer, 0, rState.Buffer.Length,
                           SocketFlags.None, new AsyncCallback(socketReadCallBack), rState);

                        dataRead = 0;
                    }
                }
            }
            else
            {
                // Stream closed, but have we read everything ?
                if (LastrStateDataLength + dataRead == rState.DataSize)
                {
                    // We're equal, get ready for more
                    //no more data remaining to process - issue another receive
                    if (_IsConnected)
                    {
                        client.BeginReceive(rState.Buffer, 0, rState.Buffer.Length,
                           SocketFlags.None, new AsyncCallback(socketReadCallBack),
                              rState);
                    }
                    return;
                }
                else
                {
                    // We should have more..
                    // Report Error
                }
            }

            // If we've been disconnected, provide a graceful exit
            if (!_IsConnected)
                dataRead = -1;

        }
     }

我在这里得到的东西比你需要的东西要多,比如提供一个心跳消息,并在连接丢失等情况下提出事件。