使用tcp在同一台机器上进行进程间通信

时间:2012-11-03 03:51:53

标签: c#-4.0 inter-process-communicat

我有两个进程客户端和服务器。 这是以下内容: 这是我的客户流程: -

[Serializable ]
public class retobj
{
    public int a;

}
class client
{
    static void Main(string[] args)
    {
        TcpClient client = new TcpClient();
        client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5005));
        Console.WriteLine("Connected.");
        retobj ob = new retobj();
        ob.a = 90;
        BinaryFormatter bf = new BinaryFormatter();
        NetworkStream ns = client.GetStream();
        bf.Serialize(ns, ob);
        Console.WriteLine("Data sent.");
        Console.ReadLine();
        ns.Close();
        client.Close();
    }
}

这是我的服务器进程:

[Serializable]
public class retobj
{
    public int a;

}
class server
{
    static void Main(string[] args)
    {
        TcpListener listener = new TcpListener(IPAddress.Any, 5005);
        listener.Start();
        Console.WriteLine("Server started.");
        Socket client = listener.AcceptSocket();
        Console.WriteLine("Accepted client {0}.\n", client.RemoteEndPoint);
        List<string> l = null;
        retobj j = null;
        using (NetworkStream ns = new NetworkStream(client))
        {
            BinaryFormatter bf = new BinaryFormatter();
            j = (retobj )bf.Deserialize(ns);
        }
        //if (l != null)
        //    foreach (var item in l)
        //        Console.WriteLine(item);
        Console.WriteLine(j.a);
        Console.ReadLine();
        client.Close();
        listener.Stop();
    }

但是它给出了一个错误: 服务器进程出错: 无法找到程序集'ConsoleApplication45,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null'。

1 个答案:

答案 0 :(得分:2)

使用BinaryFormatter序列化对象时,它包含有关对象来自哪个程序集的信息。在服务器上反序列化时,它会读取该信息并从客户端程序集中查找retobj的版本,这就是您收到该错误的原因。服务器上的那个不一样。

尝试将该类移动到类库项目,并从客户端和服务器引用该项目。您不需要两份副本。

另一种方法是使用不嵌入汇编信息的替代格式化程序,如DataContractSerializer