首页 文章

C#Stream Dictionary问题

提问于
浏览
0

发送 - Socket.send(ToSend);

public static byte[] ToSend() {
    Dictionary<int, int> D = new Dictionary<int, int>() { {1,10},{2,88} };
    List<int> L = new List<int>() { {22}, {44} };
    var binFormatter = new BinaryFormatter();
    var mStream = new MemoryStream();
    binFormatter.Serialize(mStream, D);
    //binFormatter.Serialize(mStream, L);
    return mStream.ToArray();
}

接收 - (带异步)if(Socket.EndReceive(ar)> 0){Load(bytes);}

public static void Load(byte[] bytes) {
        var mStream = new MemoryStream();
        var binFormatter = new BinaryFormatter();
        mStream.Write(bytes, 0, bytes.Length);
        mStream.Seek(0, SeekOrigin.Begin);
        var myObject = binFormatter.Deserialize(mStream) as Dictionary<int, int>;
        //var myObject = binFormatter.Deserialize(mStream) as List<int>;
        Console.WriteLine(">> " + myObject[1]);
    }

问题:列表工作正常但字典没有,抛出异常如:“在分析完成之前,遇到了流的结尾 . ”有人可以告诉我为什么吗?问题出在哪儿? Hashtables也适用于上面的代码 . 为什么Dictionarys不这样做?

编辑:发送是在客户端调用刚刚连接简单的send();只是为了测试 .

socket.Send(ToSend());

接收在服务器端:

socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(this.RecMessage), this);

RecMessage看起来像这样:

if (socket.EndReceive(result) > 0) {Message Msg = new Message(buffer);}

在Message中很简单:

Public Message(byte[] buffer){Load(buffer);}

Hashtables正在工作,列表正在工作,Int,String或我使用的任何工作但不是字典 . 也许是Begin和End Receive有些问题?

EDIT2:将缓冲区更改为[2048]解决了问题所以问题在于开始和编辑接收 . 它应该如何正确构建?

1 回答

  • 0

    好的,解决了 . 我在收到时发送和缓冲管理器时添加了前缀:

    const int PrefixSize = 4;
        bool prefixSet = false;
        public int DataSize = 0; 
        int RecLength = 0;
        byte[] Received = new byte[2048];
    
           try {
                int dataRead = socket.EndReceive(ar);
                if (dataRead > 0) {
                    Buffer.BlockCopy(buffer, 0, Received, RecLength , dataRead);
                    RecLength += dataRead;
                    if (RecLength >= PrefixSize) {
                        if (!prefixSet) {
                            prefixSet = true;
                            DataSize = BitConverter.ToInt32(Received, 0);
                        }
                        if (RecLength >= DataSize) {
                            RecLength = 0; prefixSet = false; 
                            byte[] data = new byte[DataSize];
                            Buffer.BlockCopy(Received, 4, data, 0, DataSize);
                            ReceiveNextMessage();
                            Message m = new Message(this, data);
                        }
                        else {
                            ReceiveNextMessage();
                        }
                    }
                    else {
                        ReceiveNextMessage();
                    }
                }
    
            }
            catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
    

    也许有人发现它很有用 .

相关问题