Problem with Socket and Serialization C#

前端 未结 6 1072
陌清茗
陌清茗 2021-01-27 13:23

I implemented a Client and Server model that uses Socket with thread

When I want to pass only a string from Client to the Server, it works. But I want to pass an object

6条回答
  •  闹比i
    闹比i (楼主)
    2021-01-27 13:47

    Another question: I copied the class Command from Client and pasted at Server to deserialize. Is this correct?

    No. The namespace for your Client and Server are likely different, so the Server will be trying to deserialize a stream that matches its namespace.

    You should create your Command Class using its own namespace and reference that from both your Client and the Server.

    After that...

    Client:

    static void StreamToServer(TcpClient client, Command obj) {
      using (NetworkStream ns = client.GetStream()) {
        using (MemoryStream ms = new MemoryStream()) {
          BinaryFormatter formatter = new BinaryFormatter();
          formatter.Serialize(ms, obj);
          byte[] buf = ms.ToArray();
          ns.Write(buf, 0, buf.Length);
        }
      }
    }
    

    Server:

    static Command ReadStream(TcpListener listener) {
      Command obj = null;
      using (TcpClient client = listener.AcceptTcpClient()) { // waits for data
        using (NetworkStream ns = client.GetStream()) {
          byte[] buf = new byte[client.ReceiveBufferSize];
          int len = ns.Read(buf, 0, buf.Length);
          using (MemoryStream ms = new MemoryStream(buf, 0, len)) {
            BinaryFormatter formatter = new BinaryFormatter();
            obj = formatter.Deserialize(ms) as Command;
          }
        }
      }
      return obj;
    }
    

    WCF or Message framing may be easier, but I don't often have the opportunity at work to sit around and read a book.

提交回复
热议问题