本文介绍了造成连接插座.BeginReceive后立即接受新的消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我做了一个套接字连接。这里是我的WaitData方式:

Basically I've made a socket connection. Here's my WaitData method:

    public void WaitForData()
    {
        State state = new State();
        state.Client = socket;
        //issue first receive
        state.Client.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ServerReadCallback), state);
    }

这就是所谓每当我的插座等待数据(我希望它等待数据的所有时间)。
所以每当一个新的消息已经开始接收(.BeginReceive叫)我希望我的主线程再次调用WaitForData因此它会继续接受邮件。
这将如何做?

This is called whenever my socket is waiting for data (I want it to wait for data all the time).So whenever a new message has started to be received (.BeginReceive is called) I want my main thread to call WaitForData again so it'll keep accepting messages.How would this be done?

(顺便说一句,我不能叫WaitForData在ServerReadCallback因为它会阻止消息的实际接收)。

(btw I can't call WaitForData in the ServerReadCallback since it would block for the actual receiving of the message).

很抱歉,如果我的描述是混乱的;我发现它,而很难形容。

Sorry if my description is messy; I found it rather hard to describe.

推荐答案

在您的日常ServerReadCallBack一旦你finsished处理消息,另一个问题,即BeginReceive

In your ServerReadCallBack routine once you've finsished processing the message, issue another BeginReceive ie:

    State state = new State();
    state.Client = socket;
    //issue first receive
    state.Client.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ServerReadCallback), state);



记住然而,如果你的消息是可变长度,然后在缓冲区中读取的数据可能是部分消息;整个消息;或整个另一消息的消息加部分/全体。所以,你的ServerReadCallback需要能够处理这个 - 线沿线的东西:

Bear in mind however if your messages are variable length, then the data read in a buffer may be part of a message; the whole of a message; or the whole of a message plus part/whole of another message. So your ServerReadCallback needs to be able to deal with this - something along the lines of:

    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)
        {
           // Your code goes here..
        }

        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 ?
                    // This is my own thing - you may not need this..
                    if (rState.Data.Length == 2)
                    {
                        // Yes
                        HeartBeatReceived();
                    }
                    else

                    {
                       // Handle the received messsage

                        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;

        }
     }

在这段代码我rstate是:

In this code my rstate is:

public class ReceiveState
{
    public byte[] Buffer = new byte[1024]; //buffer for network i/o
    public int DataSize = 0; //data size to be received by the server
    public bool DataSizeReceived = false; //whether prefix was received
    public MemoryStream Data = new MemoryStream(); //place where data is stored
    public Socket Client;   //client socket
}

这篇关于造成连接插座.BeginReceive后立即接受新的消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:20