使用Socket接收数据包

时间:2013-05-20 14:22:32

标签: c# sockets

我是Socket编程的新手,我只是想问一些事情。

我试图在客户端和服务器之间创建简单接收器和发件人数据包(我正在使用同一台计算机),但我遇到了问题......

发送功能正常,但我不知道如何接收以完全相同的数据包发送的数据包。

例如,我从客户端向服务器发送5个字节,我只想服务器只接收5个字节,不多也不少,我想用Socket做这个,我也已经包含了大小短(int16 2字节)格式的数据包。这是我发送的数据包代码:

    public static void Send(Socket socket, byte[] buffer, int timeout)
    {
        int startTickCount = Environment.TickCount;
        int sent = 0;
        int offset = 0;
        int size = buffer.Length;

        // Add size of packet in the begin of data packet with short (int16) format
        List<byte> tmpdata = new List<byte>();
        tmpdata.AddRange(BitConverter.GetBytes((short)(buffer.Length + 2)));
        tmpdata.AddRange(buffer);
        buffer = tmpdata.ToArray();

        do
        {
            if (Environment.TickCount > startTickCount + timeout)
                throw new Exception("Sending packet was timeout.");
            try
            {
                sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.WouldBlock ||
                    ex.SocketErrorCode == SocketError.IOPending ||
                    ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
                {
                    Thread.Sleep(30);
                }
                else
                    throw ex;
            }
        } while (sent < size);
    }

有人可以帮助我吗?


感谢Damien的修复 我找到了解决方案,但我担心这会消耗内存使用量,因为它循环每个字节,这里是代码:

    public static byte[] Receive(Socket socket)
    {
        System.Net.Sockets.NetworkStream ns = new NetworkStream(socket);
        int b = (byte)1;
        List<byte> databuf = new List<byte>();

        while ((b = ns.ReadByte()) != -1)
            databuf.Add((byte)b);

        return databuf.ToArray();
    }

有没有更好的解决方案没有NetworkStream或者更好的性能? 感谢

2 个答案:

答案 0 :(得分:3)

您没有显示接收代码,但可以轻松修复一个错误:

    // Add size of packet in the begin of data packet with short (int16) format
    List<byte> tmpdata = new List<byte>();
    tmpdata.AddRange(BitConverter.GetBytes((short)(buffer.Length + 2)));
    tmpdata.AddRange(buffer);
    buffer = tmpdata.ToArray();
    int size = buffer.Length; //Moved from higher up, now that buffer is a different size

在接收方,你应该有类似的代码 - 循环,直到你读了2个字节,用它来创建一个short,这是要接收的总大小,减去2(老实说,我只是避免在上面的代码中添加2并将大小发送为忽略用于编码大小的实际字节的大小),然后再次循环直到您已阅读整个消息。

答案 1 :(得分:1)

  

有没有更好的解决方案没有NetworkStream或者可能有更好的性能?

NetworkStream充当Socket的更高级别包装器,因此您可以直接使用它做同样的事情:

var targetStream = new MemoryStream();
var buffer = new byte[receiveBufferSize];
int bytesReceived = 0;

while ((bytesReceived = socket.Receive(buffer)) > 0)
{
    targetStream.Write(buffer, 0, bytesReceived);
}

SendAsync中的ReceiveAsyncSocket方法在您需要执行多个并发操作时也能正常运行。但它们更复杂:

var receive = new SocketAsyncEventArgs();
var receiveBuffer = new byte[receiveBufferSize];
receive.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
receive.Completed += HandleReceived;

if (!socket.ReceiveAsync(receive))
{
    HandleReceived(this, receive);
}