0

我是套接字编程的新手,我只是想问一些问题。

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

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

例如,我从客户端向服务器发送 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 或者更好的性能有没有更好的解决方案?谢谢

4

2 回答 2

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 和将大小发送为忽略用于编码大小的实际字节的大小),然后再次循环,直到您阅读了整个消息。

于 2013-05-20T14:56:15.443 回答
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);
}
于 2013-05-20T16:29:26.037 回答