C#TCP套接字回调不返回第一个发送消息的字节

时间:2018-06-22 20:05:40

标签: c# sockets

我有一个控制台应用程序,用于监听客户端套接字连接和正在发送的数据包。发送数据包后,它将输出数据包的长度。我试图为我的应用程序创建更多的组织,并将其中一些操作保留在自己的对象中。但是,我遇到了一个小问题,第一个消息返回为0,但其余消息都很好。

我有一个处理接收到的数据的对象:

public class Receiver : IDisposable
{
    private byte[] _buffer;
    public Receiver(byte[] buffer)
    {
        this._buffer = buffer;
    }

    public void DoWork(IAsyncResult result)
    {
        Socket clientSocket = (Socket)result.AsyncState;
        int bufferSize = clientSocket.EndReceive(result);
        byte[] packet = new byte[bufferSize];
        Array.Copy(_buffer, packet, packet.Length);

        // Handle the packet
        ushort packetLength = BitConverter.ToUInt16(packet, 0);

        Console.WriteLine("Packet received... Length: {0}", packetLength);

        _buffer = new byte[1024];
        clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, this.DoWork, clientSocket);
    }

    public void Dispose()
    {

    }
}

处理传入连接的对象:

public class Connector : IDisposable
{
    private Socket _socket;
    private Receiver _receiver;
    private byte[] _buffer;
    public Connector(Socket socket, Receiver receiver, byte[] buffer)
    {
        this._socket = socket;
        this._receiver = receiver;
        this._buffer = buffer;
    }

    public void DoWork()
    {
        _socket.BeginAccept(this.HandleAcceptedCallback,null);

    }

    public void Dispose()
    {

    }

    private void HandleAcceptedCallback(IAsyncResult result)
    {
        Socket clientSocket = _socket.EndAccept(result);
        _buffer = new byte[1024];
        clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, _receiver.DoWork, clientSocket);
        this.DoWork();
    }
}

然后是我的控制台对象:

static void Main(string[] args)
    {
        byte[] buffer = new byte[1024];
        using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        using (Receiver receiver = new Receiver(buffer))
        using (Connector connector = new Connector(socket, receiver, buffer))
        {
            socket.Bind(11000);
            socket.Listen(500);
            connector.DoWork();

            while (true)
                Console.ReadLine();
        }
    }

我一直在尝试不同的方法,并且发现如果我将DoWork对象中的Receiver方法移到Connector对象中并将回调连接到那里,一切正常。

我想知道是否有人可以告诉我我要去哪里错了,或者为什么这不切实际?我不熟悉使用套接字,对于任何误解表示歉意。

0 个答案:

没有答案